Red and Green Ignored Bar by Oliver VelezOn this occasion I present a script that detects Ignored Red Candles and Ignored Green Candles, basically it is a Price Action event that indicates a possible continuation of the current trend and gives the opportunity to climb it with a Very tight risk, before delving into detail I would like to leave this note:
Note: the detection of this event does not guarantee that the signal will be good, the trader must have the ability to determine its quality based on aspects such as trend, maturity, support / resistance levels, expansion / contraction of the market, risk / benefit, etc, if you do not have knowledge about this you should not use this indicator since using it without a robust trading plan and experience could cause you to partially or totally lose your money, if this is your case you should train before If you try to extract money from the market, this script was created to be another tool in your trading plan in order to configure the rules at your discretion, execute them consistently and have AUTOMATIC ALERTS when the event occurs, which is where I find more value because you can have many instruments waiting for the event to be generated, in the time frame you want and without having to observe the mer When the alert is generated, the Trader should evaluate the quality of the alert and define whether or not to execute it (higher timeframes, they can give you more time to execute the operation correctly).
Let's continue….
This event was created by Oliver Velez recognized trader / mentor of price action, the event has a very interesting particularity since it allows to take a position with a very limited risk in trend movements, this achieves favorable operations of good ratio and small losses when taking An adjusted risk, if the trade works, a good ratio is quickly achieved and we agree with a key point in the “Keep small losses and big profits” trading, this makes it easier to have a positive mathematical hope when your level of Success is not very high, so leave you in the field of profitability.
THE EVENT:
The event has a bullish configuration (Ignored Red Candle) and a bearish configuration (Ignored Green Candle), below I detail the “Hard” rules (later I explain why “Hard”):
1- Last 3 bars have to be GREEN-RED-GREEN (possible bullish configuration) or RED-GREEN-RED (possible bearish configuration), the first bar is called Control Bar, the second is called Ignored Bar and the third Signal Bar as shown in the following image:
2- Be in a trend determined by simple moving averages (Slow of 20 periods and Fast of 8 periods), as a general rule you can take the direction of MA20 but the Trader has to determine if there is a trend movement or not.
3- Control bar of good range, little tail and with a body greater than 55%.
4- Ignored bar preferably narrow range, little tail and that is located in the upper 1/3 of the control bar.
5- Signal bar cannot override the minimum of the ignored bar.
6- Activation / Confirmation of event by means of signal bar in overcoming the body of the ignored bar.
Some examples of ignored bars (with “Hard” and “Flexible” rules):
Features and configuration of the indicator:
To access the indicator settings, press the wheel next to the indicator name VVI_VRI "Configuration options".
- Operation mode (Filtering Type):
• Filtering Complete: all filters activated according to the configuration below.
• Without Filtering: all filters deactivated, all VRI / VVI are displayed without any selection criteria.
• Trend Filter only: shows only VRI / VVI that are in accordance with what is set in “Trend Settings”
- Configuration Moving Averages:
• See Slow Media: slow moving average display with direction detection and color change.
• See Fast Media: display of fast moving average with direction detection and color change.
• Type: possibility to choose the type of media: DEMA, EMA, HullMA, SMA, SSMA, SSMA, TEMA, TMA, VWMA, WMA, ZEMA)
• Period: number of previous bars.
• Source: possibility to choose the type of source, open, close, high, low, hl2 hlc3, ohlc4.
• Reaction: this configuration affects the color change before a change of direction, 1 being an immediate reaction and higher values, a more delayed reaction obtaining les false "changes of direction", a value of 3 filters the direction quite well.
- Trend Configuration
• Uptrend Condition P / VRI: possibility to select any of these conditions:
o Bullish MA direction
o Quick bullish MA direction
o Slow and fast bullish MA direction
o Price higher than slow MA
o Price higher than fast MA
o Price higher than slow and fast MA
o Price higher than slow MA and bullish direction
o Price higher than fast MA and bullish direction
o Price higher than slow, fast MA and bullish direction
o No condition
• Condition P / VVI bear trend: possibility of selecting any of these conditions:
o Slow bearish MA direction
o Fast bearish MA direction
o Slow and fast bearish MA direction
o Price less than slow MA
o Price less than fast MA
o Price less than slow and fast MA
o Price lower than slow MA and bearish direction
o Price less than fast MA and bearish direction
o Price less than slow, fast MA and bearish direction
o No condition
- Control bar configuration
• Minimum body percentage%: possibility to select what body percentage the bar must have.
• Paint control bar: when selected, paint the control bar.
• See control bar label: when selected, a label with the legend BC is plotted.
- Configuration bar ignored
• Above X% of the control bar: possibility to select above what percentage of the control bar the ignored bar must be located.
• Paint ignored bar: when selected, paint the ignored bar.
- Signal bar configuration
• You cannot override the minimum of the ignored bar: when selected, the condition is added that the signal bar cannot override the minimum of the ignored bar.
• Paint signal bar: when selected, paint the signal bar.
• See arrow: when selected it shows the direction arrow of the possible movement.
• See bear and arrow: when selected it shows bear and arrow label
• See bull and arrow: when selected it shows bull and arrow label
The following image shows the ignored bar and painted signal:
- Take profit / loss
The profit / loss taking varies depending on the trader and its risk / monetary plan, the proposal is a recommendation based on the nature of the event that is to have a small risk unit (stop below the minimum of the ignored bar), look for objectives in ratios greater than 2: 1 and eliminate the risk in 1: 1 by taking the stop to BE, all parameters are configurable and are the following:
• See recommended stop loss and take profit: trace the levels of Stop, BE, TP1 and TP2, as well as their prices to know them quickly based on the assumed risk
• To: select which event you want to draw the SL and TP (VRI, VVI)
• Extend stop loss line x bars: allows extending the stop line by x number of bars
• Extend take profit line x bars: allows extending the stop line by x number of bars
• Ratio to move to break even: allows you to select the minimum ratio to move stop to break even (default 1: 1)
• Take profit 1 ratio: allows you to select the ratio for take profit 1 (default 2: 1)
• Take profit 2 ratio: allows you to select the ratio for take profit 2 (default 4: 1)
- Alerts
• It is possible to configure the following alerts:
-VRI DETECTED
-VVI DETECTED
-VRI / VVI DETECTED
Final Notes:
- The term hard rules refers to the fact that an event is sought with the rules detailed above to obtain a high quality event but this brings 2 situations to consider, less
number of events and events that are generated in a strong impulse may be leaked, a very large control bar followed by an ignored narrow body away from moving averages, despite having a good chance of continuing, taking a stop very tight in a strong impulse you can touch it by the simple fact of the own volatility at that time.
- The setting of the parameters “Minimum body percentage% (control bar)”, “Above x% of the control bar (bar ignored)” and “Cannot override the minimum of the ignored bar” can bring large Benefits in terms of number of events and that can also be of high quality, feel free to find the best configuration for your instrument to operate.
- It is recommended to look for trending events, near moving averages and at an early stage of it.
- The display of several nearby VRIs or VVIs in an advanced trend may indicate a depletion of it.
- The alerts can be worked in 2 ways: at the closing of the candle (confirms event but the risk unit may be larger or smaller) or immediately the body of the ignored bar is exceeded, in case you are operating from the mobile and miss many events because of the short time I recommend that you operate in a superior time frame to have more time.
- The indicator is configured with “flexible” rules to have more events, but without any important criteria, each trader has to look for the best configuration that suits his instrument.
- It is recommended to partially close the operation based on the ratio and always keep a part of the position to apply manual trailing stop and try to maximize profits.
The code is open feel free to use and modify it, a mention in credits is appreciated.
If you liked this SCRIPT THUMB UP!
Greetings to all, I wish you much green!
Cerca negli script per "stop loss"
Camarilla Pivots + 20 EMA StrategyThis is an intraday volatility and trend-following system for commodities like Natural Gas, combining dynamic pivot levels (Camarilla) with a trend filter (20-period EMA) to improve risk-reward and reduce false breakouts.
Core Components
1. Camarilla Pivots:
These are special support and resistance levels (H3, H4, L3, L4) calculated each day based on the previous day's high, low, and close.
The pivots adapt to daily volatility, giving more relevant breakout and bounce zones than static lines.
H4: Aggressive resistance (used for breakout LONG entry)
H3: Moderate resistance/support (used for bounce or stoploss)
L4: Aggressive support (used for breakout SHORT entry)
L3: Moderate support/resistance (used for bounce or stoploss)
2. 20 EMA (Exponential Moving Average):
Plotted on the 30-minute chart, this acts as a trend filter.
If the price is above 20 EMA: Only look for long trades (bullish bias).
If below 20 EMA: Only look for short trades (bearish bias).
How the Strategy Works
Setup (30-Min Chart):
Camarilla pivots for the day are drawn on the chart.
20 EMA is also plotted.
Trade Filter:
Bullish: Trade ONLY if price is above 20 EMA.
Bearish: Trade ONLY if price is below 20 EMA.
Entry:
LONG: Enter when price breaks and closes above the H4 pivot AND is above 20 EMA.
SHORT: Enter when price breaks and closes below the L4 pivot AND is below 20 EMA.
Stop Loss:
LONG: Place stoploss at H3 (the next lower Camarilla resistance).
SHORT: Place stoploss at L3 (the next higher Camarilla support).
Target:
Always set a profit target at 2x the distance (risk) between entry and stoploss (strict R:R 2).
For example, if your entry is at H4 and stoploss at H3, your target is entry + 2*(entry - stoploss).
Alerts & Visuals:
The strategy plots entry arrows, stoploss and target lines for immediate visual reference.
Alerts trigger on breakout signals so you never miss a trade.
Why This Works Well for Natural Gas
Adapts to volatility: The pivots change daily, handling wide-ranging and choppy price moves better than fixed breakouts.
Trend filter: EMA prevents counter-trend whipsaws, only trades with market momentum.
Risk control: Every trade must meet strict risk-reward criteria, so losses are contained and winners can outweigh losers.
Luxy Momentum, Trend and Breakout Indicators Suit V6TABLE OF CONTENTS
This is Version 6 (V6) - the latest and most optimized release. If you are using any older versions (V5, V4, V3, etc.), it is highly recommended to replace them with V6.
Why This Indicator is Different
Who Should Use This
Core Components Overview
The UT Bot Trading System
Understanding the Market Bias Table
Candlestick Pattern Recognition
Visual Tools and Features
How to Use the Indicator
Performance and Optimization
FAQ
---
1. WHY THIS INDICATOR IS DIFFERENT
Most traders use multiple separate indicators on their charts, leading to cluttered screens, conflicting signals, and analysis paralysis. The Suite solves this by integrating proven technical tools into a single, cohesive system.
Key Advantages:
All-in-One Design: Instead of loading 5-10 separate indicators, you get everything in one optimized script. This reduces chart clutter and improves TradingView performance.
Multi-Timeframe Bias Table: Unlike standard indicators that only show the current timeframe, the Bias Table aggregates trend signals across multiple timeframes simultaneously. See at a glance whether 1m, 5m, 15m, 1h are aligned bullish or bearish - no more switching between charts.
Smart Confirmations: The indicator doesn't just give signals - it shows you WHY. Every entry has multiple layers of confirmation (MA cross, MACD momentum, ADX strength, RSI pullback, volume, etc.) that you can toggle on/off.
Dynamic Stop Loss System: Instead of static ATR stops, the SL is calculated from multiple support/resistance layers: UT trailing line, Supertrend, VWAP, swing structure, and MA levels. This creates more intelligent, price-action-aware stops.
R-Multiple Take Profits: Built-in TP system calculates targets based on your initial risk (1R, 1.5R, 2R, 3R). Lines freeze when touched with visual checkmarks, giving you a clean audit trail of partial exits.
Educational Tooltips Everywhere: Every single input has detailed tooltips explaining what it does, typical values, and how it impacts trading. You're not guessing - you're learning as you configure.
Performance Optimized: Smart caching, conditional calculations, and modular design mean the indicator runs fast despite having 15+ features. Turn off what you don't use for even better performance.
No Repainting: All signals respect bar close. Alerts fire correctly. What you see in history is what you would have gotten in real-time.
What Makes It Unique:
Integrated UT Bot + Bias Table: No other indicator combines UT Bot's ATR trailing system with a live multi-timeframe dashboard. You get precision entries with macro trend context.
Candlestick Pattern Recognition with Interactive Tooltips: Patterns aren't just marked - hover over any emoji for a full explanation of what the pattern means and how to trade it.
Opening Range Breakout Tracker: Built-in ORB system for intraday traders with customizable session times and real-time status updates in the Bias Table.
Previous Day High/Low Auto-Detection: Automatically plots PDH/PDL on intraday charts with theme-aware colors. Updates daily without manual input.
Dynamic Row Labels in Bias Table: The table shows your actual settings (e.g., "EMA 10 > SMA 20") not generic labels. You know exactly what's being evaluated.
Modular Filter System: Instead of forcing a fixed methodology, the indicator lets you build your own strategy. Start with just UT Bot, add filters one at a time, test what works for your style.
---
2. WHO WHOULD USE THIS
Designed For:
Intermediate to Advanced Traders: You understand basic technical analysis (MAs, RSI, MACD) and want to combine multiple confirmations efficiently. This isn't a "one-click profit" system - it's a professional toolkit.
Multi-Timeframe Traders: If you trade one asset but check multiple timeframes for confirmation (e.g., enter on 5m after checking 15m and 1h alignment), the Bias Table will save you hours every week.
Trend Followers: The indicator excels at identifying and following trends using UT Bot, Supertrend, and MA systems. If you trade breakouts and pullbacks in trending markets, this is built for you.
Intraday and Swing Traders: Works equally well on 5m-1h charts (day trading) and 4h-D charts (swing trading). Scalpers can use it too with appropriate settings adjustments.
Discretionary Traders: This isn't a black-box system. You see all the components, understand the logic, and make final decisions. Perfect for traders who want tools, not automation.
Works Across All Markets:
Stocks (US, international)
Cryptocurrency (24/7 markets supported)
Forex pairs
Indices (SPY, QQQ, etc.)
Commodities
NOT Ideal For:
Complete Beginners: If you don't know what a moving average or RSI is, start with basics first. This indicator assumes foundational knowledge.
Algo Traders Seeking Black Box: This is discretionary. Signals require context and confirmation. Not suitable for blind automated execution.
Mean-Reversion Only Traders: The indicator is trend-following at its core. While VWAP bands support mean-reversion, the primary methodology is trend continuation.
---
3. CORE COMPONENTS OVERVIEW
The indicator combines these proven systems:
Trend Analysis:
Moving Averages: Four customizable MAs (Fast, Medium, Medium-Long, Long) with six types to choose from (EMA, SMA, WMA, VWMA, RMA, HMA). Mix and match for your style.
Supertrend: ATR-based trend indicator with unique gradient fill showing trend strength. One-sided ribbon visualization makes it easier to see momentum building or fading.
ZLSMA: Zero-lag linear-regression smoothed moving average. Reduces lag compared to traditional MAs while maintaining smooth curves.
Momentum & Filters:
MACD: Standard MACD with separation filter to avoid weak crossovers.
RSI: Pullback zone detection - only enter longs when RSI is in your defined "buy zone" and shorts in "sell zone".
ADX/DMI: Trend strength measurement with directional filter. Ensures you only trade when there's actual momentum.
Volume Filter: Relative volume confirmation - require above-average volume for entries.
Donchian Breakout: Optional channel breakout requirement.
Signal Systems:
UT Bot: The primary signal generator. ATR trailing stop that adapts to volatility and gives clear entry/exit points.
Base Signals: MA cross system with all the above filters applied. More conservative than UT Bot alone.
Visual Intelligence:
Market Bias Table: Multi-timeframe dashboard showing trend alignment across 7 timeframes plus macro bias (3-day, weekly, monthly, quarterly, VIX).
Candlestick Patterns: Six major reversal patterns auto-detected with interactive tooltips.
ORB Tracker: Opening range high/low with breakout status (intraday only).
PDH/PDL: Previous day levels plotted automatically on intraday charts.
VWAP + Bands: Session-anchored VWAP with up to three standard deviation band pairs.
---
4. THE UT BOT TRADING SYSTEM
The UT Bot is the heart of the indicator's signal generation. It's an advanced ATR trailing stop that adapts to market volatility.
Why UT Bot is Superior to Fixed Stops:
Traditional ATR stops use a fixed multiplier (e.g., "stop = entry - 2×ATR"). UT Bot is smarter:
It TRAILS the stop as price moves in your favor
It WIDENS during high volatility to avoid premature stops
It TIGHTENS during consolidation to lock in profits
It FLIPS when price breaks the trailing line, signaling reversals
Visual Elements You'll See:
Orange Trailing Line: The actual UT stop level that adapts bar-by-bar
Buy/Sell Labels: Aqua triangle (long) or orange triangle (short) when the line flips
ENTRY Line: Horizontal line at your entry price (optional, can be turned off)
Suggested Stop Loss: A composite SL calculated from multiple support/resistance layers:
- UT trailing line
- Supertrend level
- VWAP
- Swing structure (recent lows/highs)
- Long-term MA (200)
- ATR-based floor
Take Profit Lines: TP1, TP1.5, TP2, TP3 based on R-multiples. When price touches a TP, it's marked with a checkmark and the line freezes for audit trail purposes.
Status Messages: "SL Touched ❌" or "SL Frozen" when the trade leg completes.
How UT Bot Differs from Other ATR Systems:
Multiple Filters Available: You can require 2-bar confirmation, minimum % price change, swing structure alignment, or ZLSMA directional filter. Most UT implementations have none of these.
Smart SL Calculation: Instead of just using the UT line as your stop, the indicator suggests a better SL based on actual support/resistance. This prevents getting stopped out by wicks while keeping risk controlled.
Visual Audit Trail: All SL/TP lines freeze when touched with clear markers. You can review your trades weeks later and see exactly where entries, stops, and targets were.
Performance Options: "Draw UT visuals only on bar close" lets you reduce rendering load without affecting logic or alerts - critical for slower machines or 1m charts.
Trading Logic:
UT Bot flips direction (Buy or Sell signal appears)
Check Bias Table for multi-timeframe confirmation
Optional: Wait for Base signal or candlestick pattern
Enter at signal bar close or next bar open
Place stop at "Suggested Stop Loss" line
Scale out at TP levels (TP1, TP2, TP3)
Exit remaining position on opposite UT signal or stop hit
---
5. UNDERSTANDING THE MARKET BIAS TABLE
This is the indicator's unique multi-timeframe intelligence layer. Instead of looking at one chart at a time, the table aggregates signals across seven timeframes plus macro trend bias.
Why Multi-Timeframe Analysis Matters:
Professional traders check higher and lower timeframes for context:
Is the 1h uptrend aligning with my 5m entry?
Are all short-term timeframes bullish or just one?
Is the daily trend supportive or fighting me?
Doing this manually means opening multiple charts, checking each indicator, and making mental notes. The Bias Table does it automatically in one glance.
Table Structure:
Header Row:
On intraday charts: 1m, 5m, 15m, 30m, 1h, 2h, 4h (toggle which ones you want)
On daily+ charts: D, W, M (automatic)
Green dot (🟢) next to title = live updating
Headline Rows - Macro Bias:
These show broad market direction over longer periods:
3 Day Bias: Trend over last 3 trading sessions (uses 1h data)
Weekly Bias: Trend over last 5 trading sessions (uses 4h data)
Monthly Bias: Trend over last 30 daily bars
Quarterly Bias: Trend over last 13 weekly bars
VIX Fear Index: Market regime based on VIX level - bullish when low, bearish when high
Opening Range Breakout: Status of price vs. session open range (intraday only)
These rows show text: "BULLISH✔️", "BEARISH✖️", or "NEUTRAL⚠️"
Indicator Rows - Technical Signals:
These evaluate your configured indicators across all active timeframes:
Fast MA > Medium MA (shows your actual MA settings, e.g., "EMA 10 > SMA 20")
Price > Long MA (e.g., "Price > SMA 200")
Price > VWAP
MACD > Signal
Supertrend (up/down/neutral)
ZLSMA Rising
RSI In Zone
ADX ≥ Minimum
These rows show emojis: 🟩 (bullish), 🟥 (bearish), 🟡 (neutral/NA)
AVG Column:
Shows percentage of active timeframes that are bullish for that row. This is the KEY metric:
AVG > 70% = strong multi-timeframe bullish alignment
AVG 40-60% = mixed/choppy, no clear trend
AVG < 30% = strong multi-timeframe bearish alignment
How to Use the Table:
For a long trade:
Check AVG column - want to see > 60% ideally
Check headline bias rows - want to see BULLISH, not BEARISH
Check VIX row - bullish market regime preferred
Check ORB row (intraday) - want ABOVE for longs
Scan indicator rows - more green = better confirmation
For a short trade:
Check AVG column - want to see < 40% ideally
Check headline bias rows - want to see BEARISH, not BULLISH
Check VIX row - bearish market regime preferred
Check ORB row (intraday) - want BELOW for shorts
Scan indicator rows - more red = better confirmation
When AVG is 40-60%:
Market is choppy, mixed signals. Either stay out or reduce position size significantly. These are low-probability environments.
Unique Features:
Dynamic Labels: Row names show your actual settings (e.g., "EMA 10 > SMA 20" not generic "Fast > Slow"). You know exactly what's being evaluated.
Customizable Rows: Turn off rows you don't care about. Only show what matters to your strategy.
Customizable Timeframes: On intraday charts, disable 1m or 4h if you don't trade them. Reduces calculation load by 20-40%.
Automatic HTF Handling: On Daily/Weekly/Monthly charts, the table automatically switches to D/W/M columns. No configuration needed.
Performance Smart: "Hide BIAS table on 1D or above" option completely skips all table calculations on higher timeframes if you only trade intraday.
---
6. CANDLESTICK PATTERN RECOGNITION
The indicator automatically detects six major reversal patterns and marks them with emojis at the relevant bars.
Why These Six Patterns:
These are the most statistically significant reversal patterns according to trading literature:
High win rate when appearing at support/resistance
Clear visual structure (not subjective)
Work across all timeframes and assets
Studied extensively by institutions
The Patterns:
Bullish Patterns (appear at bottoms):
🔺 Bullish Engulfing: Green candle completely engulfs prior red candle's body. Strong reversal signal.
🔨 Hammer: Small body with long lower wick (at least 2× body size). Shows rejection of lower prices by buyers.
🌅 Morning Star: Three-candle pattern (large red → small indecision → large green). Very strong bottom reversal.
Bearish Patterns (appear at tops):
🔻 Bearish Engulfing: Red candle completely engulfs prior green candle's body. Strong reversal signal.
🌠 Shooting Star: Small body with long upper wick (at least 2× body size). Shows rejection of higher prices by sellers.
🌆 Evening Star: Three-candle pattern (large green → small indecision → large red). Very strong top reversal.
Interactive Tooltips:
Unlike most pattern indicators that just draw shapes, this one is educational:
Hover your mouse over any pattern emoji
A tooltip appears explaining: what the pattern is, what it means, when it's most reliable, and how to trade it
No need to memorize - learn as you trade
Noise Filter:
"Min candle body % to filter noise" setting prevents false signals:
Patterns require minimum body size relative to price
Filters out tiny candles that don't represent real buying/selling pressure
Adjust based on asset volatility (higher % for crypto, lower for low-volatility stocks)
How to Trade Patterns:
Patterns are NOT standalone entry signals. Use them as:
Confirmation: UT Bot gives signal + pattern appears = stronger entry
Reversal Warning: In a trade, opposite pattern appears = consider tightening stop or taking profit
Support/Resistance Validation: Pattern at key level (PDH, VWAP, MA 200) = level is being respected
Best combined with:
UT Bot or Base signal in same direction
Bias Table alignment (AVG > 60% or < 40%)
Appearance at obvious support/resistance
---
7. VISUAL TOOLS AND FEATURES
VWAP (Volume Weighted Average Price):
Session-anchored VWAP with standard deviation bands. Shows institutional "fair value" for the trading session.
Anchor Options: Session, Day, Week, Month, Quarter, Year. Choose based on your trading timeframe.
Bands: Up to three pairs (X1, X2, X3) showing statistical deviation. Price at outer bands often reverses.
Auto-Hide on HTF: VWAP hides on Daily/Weekly/Monthly charts automatically unless you enable anchored mode.
Use VWAP as:
Directional bias (above = bullish, below = bearish)
Mean reversion levels (outer bands)
Support/resistance (the VWAP line itself)
Previous Day High/Low:
Automatically plots yesterday's high and low on intraday charts:
Updates at start of each new trading day
Theme-aware colors (dark text for light charts, light text for dark charts)
Hidden automatically on Daily/Weekly/Monthly charts
These levels are critical for intraday traders - institutions watch them closely as support/resistance.
Opening Range Breakout (ORB):
Tracks the high/low of the first 5, 15, 30, or 60 minutes of the trading session:
Customizable session times (preset for NYSE, LSE, TSE, or custom)
Shows current breakout status in Bias Table row (ABOVE, BELOW, INSIDE, BUILDING)
Intraday only - auto-disabled on Daily+ charts
ORB is a classic day trading strategy - breakout above opening range often leads to continuation.
Extra Labels:
Change from Open %: Shows how far price has moved from session open (intraday) or daily open (HTF). Green if positive, red if negative.
ADX Badge: Small label at bottom of last bar showing current ADX value. Green when above your minimum threshold, red when below.
RSI Badge: Small label at top of last bar showing current RSI value with zone status (buy zone, sell zone, or neutral).
These labels provide quick at-a-glance confirmation without needing separate indicator windows.
---
8. HOW TO USE THE INDICATOR
Step 1: Add to Chart
Load the indicator on your chosen asset and timeframe
First time: Everything is enabled by default - the chart will look busy
Don't panic - you'll turn off what you don't need
Step 2: Start Simple
Turn OFF everything except:
UT Bot labels (keep these ON)
Bias Table (keep this ON)
Moving Averages (Fast and Medium only)
Suggested Stop Loss and Take Profits
Hide everything else initially. Get comfortable with the basic UT Bot + Bias Table workflow first.
Step 3: Learn the Core Workflow
UT Bot gives a Buy or Sell signal
Check Bias Table AVG column - do you have multi-timeframe alignment?
If yes, enter the trade
Place stop at Suggested Stop Loss line
Scale out at TP levels
Exit on opposite UT signal
Trade this simple system for a week. Get a feel for signal frequency and win rate with your settings.
Step 4: Add Filters Gradually
If you're getting too many losing signals (whipsaws in choppy markets), add filters one at a time:
Try: "Require 2-Bar Trend Confirmation" - wait for 2 bars to confirm direction
Try: ADX filter with minimum threshold - only trade when trend strength is sufficient
Try: RSI pullback filter - only enter on pullbacks, not chasing
Try: Volume filter - require above-average volume
Add one filter, test for a week, evaluate. Repeat.
Step 5: Enable Advanced Features (Optional)
Once you're profitable with the core system, add:
Supertrend for additional trend confirmation
Candlestick patterns for reversal warnings
VWAP for institutional anchor reference
ORB for intraday breakout context
ZLSMA for low-lag trend following
Step 6: Optimize Settings
Every setting has a detailed tooltip explaining what it does and typical values. Hover over any input to read:
What the parameter controls
How it impacts trading
Suggested ranges for scalping, day trading, and swing trading
Start with defaults, then adjust based on your results and style.
Step 7: Set Up Alerts
Right-click chart → Add Alert → Condition: "Luxy Momentum v6" → Choose:
"✅UT Bot — Buy✅" for long entries
"❌UT Bot — Sell❌" for short entries
"Base Long/Short" for filtered MA cross signals
Optionally enable "Send real-time alert() on UT flip" in settings for immediate notifications.
Common Workflow Variations:
Conservative Trader:
UT signal + Base signal + Candlestick pattern + Bias AVG > 70%
Enter only at major support/resistance
Wider UT sensitivity, multiple filters
Aggressive Trader:
UT signal + Bias AVG > 60%
Enter immediately, no waiting
Tighter UT sensitivity, minimal filters
Swing Trader:
Focus on Daily/Weekly Bias alignment
Ignore intraday noise
Use ORB and PDH/PDL less (or not at all)
Wider stops, patient approach
---
9. PERFORMANCE AND OPTIMIZATION
The indicator is optimized for speed, but with 15+ features running simultaneously, chart load time can add up. Here's how to keep it fast:
Biggest Performance Gains:
Disable Unused Timeframes: In "Time Frames" settings, turn OFF any timeframe you don't actively trade. Each disabled TF saves 10-15% calculation time. If you only day trade 5m, 15m, 1h, disable 1m, 2h, 4h.
Hide Bias Table on Daily+: If you only trade intraday, enable "Hide BIAS table on 1D or above". This skips ALL table calculations on higher timeframes.
Draw UT Visuals Only on Bar Close: Reduces intrabar rendering of SL/TP/Entry lines. Has ZERO impact on logic or alerts - purely visual optimization.
Additional Optimizations:
Turn off VWAP bands if you don't use them
Disable candlestick patterns if you don't trade them
Turn off Supertrend fill if you find it distracting (keep the line)
Reduce "Limit to 10 bars" for SL/TP lines to minimize line objects
Performance Features Built-In:
Smart Caching: Higher timeframe data (3-day bias, weekly bias, etc.) updates once per day, not every bar
Conditional Calculations: Volume filter only calculates when enabled. Swing filter only runs when enabled. Nothing computes if turned off.
Modular Design: Every component is independent. Turn off what you don't need without breaking other features.
Typical Load Times:
5m chart, all features ON, 7 timeframes: ~2-3 seconds
5m chart, core features only, 3 timeframes: ~1 second
1m chart, all features: ~4-5 seconds (many bars to calculate)
If loading takes longer, you likely have too many indicators on the chart total (not just this one).
---
10. FAQ
Q: Can I use this for automated trading?
A: The indicator is designed for discretionary trading. While it has clear signals and alerts, it's not a mechanical system. Context and judgment are required.
Q: Does it repaint?
A: No. All signals respect bar close. UT Bot logic runs intrabar but signals only trigger on confirmed bars. Alerts fire correctly with no lookahead.
Q: How is this different from standard UT Bot indicators?
A: Standard UT Bot is just the ATR trailing line and flip signals. This implementation adds:
Multiple confirmation filters (swing, %, 2-bar, ZLSMA)
Smart composite stop loss system
R-multiple take profit system with freeze-on-touch
Integration with multi-timeframe Bias Table
Visual audit trail with checkmarks
Q: Do I need to use all the features?
A: Absolutely not. The indicator is modular. Many profitable traders use just UT Bot + Bias Table + Moving Averages. Start simple, add complexity only if needed.
Q: How do I know which settings to use?
A: Every single input has a detailed tooltip. Hover over any setting to see:
What it does
How it affects trading
Typical values for scalping, day trading, swing trading
Start with defaults, adjust gradually based on results.
Q: Can I use this on crypto 24/7 markets?
A: Yes. ORB will not work (no defined session), but everything else functions normally. Use "Day" anchor for VWAP instead of "Session".
Q: The Bias Table is blank or not showing.
A: Check:
"Show Table" is ON
Table position isn't overlapping another indicator's table (change position)
At least one row is enabled
"Hide BIAS table on 1D or above" is OFF (if on Daily+ chart)
Q: Why are candlestick patterns not appearing?
A: Patterns are relatively rare by design - they only appear at genuine reversal points. Check:
Pattern toggles are ON
"Min candle body %" isn't too high (try 0.05-0.10)
You're looking at a chart with actual reversals (not strong trending market)
Q: UT Bot is too sensitive/not sensitive enough.
A: Adjust "Sensitivity (Key×ATR)". Lower number = tighter stop, more signals. Higher number = wider stop, fewer signals. Read the tooltip for guidance.
Q: Can I get alerts for the Bias Table?
A: The Bias Table is a dashboard for visual analysis, not a signal generator. Set alerts on UT Bot or Base signals, then manually check Bias Table for confirmation.
Q: Does this work on stocks with low volume?
A: Yes, but turn OFF the volume filter. Low volume stocks will never meet relative volume requirements.
Q: How often should I check the Bias Table?
A: Before every entry. It takes 2 seconds to glance at the AVG column and headline rows. This one check can save you from fighting the trend.
Q: What if UT signal and Base signal disagree?
A: UT Bot is more aggressive (ATR trailing). Base signals are more conservative (MA cross + filters). If they disagree, either:
Wait for both to align (safest)
Take the UT signal but with smaller size (aggressive)
Skip the trade (conservative)
There's no "right" answer - depends on your risk tolerance.
---
FINAL NOTES
The indicator gives you an edge. How you use that edge determines results.
For questions, feedback, or support, comment on the indicator page or message the author.
Happy Trading! 🎯
15-Min RSI Scalper [SwissAlgo]15-Min RSI Scalper
Tracks RSI Momentum Loss and Gain to Generate Signals
-------------------------------------------------------
WHAT THIS INDICATOR CALCULATES
This indicator attempts to identify RSI directional changes (RSI momentum) using a step-by-step "ladder" method. It reads RSI(14) from the next higher timeframe relative to your chart. On a 15-minute chart, it uses 1-hour RSI. On a 5-minute chart, it uses 15-minute RSI, and so on.
How the ladder logic works:
The indicator doesn't track RSI all the time. It only starts tracking when RSI crosses into potentially extreme territory (these are called "events" in the code):
For sell signals : when RSI crosses above a dynamic upper threshold (typically between 60-80, calculated as the 90th percentile of recent RSI)
For buy signals : when RSI crosses below a dynamic lower threshold (typically between 20-40, calculated as the 10th percentile of recent RSI)
Once tracking begins, RSI movement is divided into 2-point steps (boxes). The indicator counts how many boxes RSI climbs or falls.
A signal generates only when:
RSI reverses direction by at least 2 boxes (4 RSI points) from its extreme
RSI holds that reversal for 3 consecutive confirmed bars
Example: Dynamic threshold is at 68. RSI crosses above 68 → tracking starts. RSI climbs to 76 (4 boxes up). Then it drops back to 72 and stays below that level for 3 bars → sell signal prints. The buy signal works the same way in reverse.
-------------------------------------------------------
SIGNAL GENERATION METHODOLOGY
Sell Signal (Red Triangle)
RSI crosses above a dynamic start level (calculated as the 90th percentile of the last 1000 bars, constrained between 60-80)
Indicator tracks upward progression in 2-point boxes
RSI reverses and drops below a boundary 2 boxes below the highest box reached
RSI remains below that boundary for 3 confirmed bars
Red triangle plots above price
Reset condition: RSI returns below 50
Buy Signal (Green Triangle)
RSI crosses below a dynamic start level (10th percentile of last 1000 bars, constrained between 20-40)
Indicator tracks downward progression in 2-point boxes
RSI reverses and rises above a boundary 2 boxes above the lowest box reached
RSI remains above that boundary for 3 confirmed bars
Green triangle plots below price
Reset condition: RSI returns above 50
-------------------------------------------------------
TECHNICAL PARAMETERS
All parameters are hardcoded:
RSI Period: 14
Box Size: 2 RSI points
Reversal Threshold: 2 boxes (4 RSI points)
Confirmation Period: 3 bars
Reset Level: RSI 50
Sell Start Range: 60-80 (dynamic)
Buy Start Range: 20-40 (dynamic)
Lookback for Percentile: 1000 bars
Note: Since the code is open source, users can modify these hardcoded values directly in the script to adjust sensitivity. For example, increasing the confirmation period from 3 to 5 bars will produce fewer but more conservative signals. Decreasing the box size from 2 to 1 will make the indicator more responsive to smaller RSI movements.
-------------------------------------------------------
KEY FEATURES
Automatic Higher Timeframe RSI
When applied to a 15-minute chart, the indicator automatically reads 1-hour RSI data. This is the next standard timeframe above 15 minutes in the indicator's logic.
Dynamic Adaptive Start Levels
Sell signals use the 90th percentile of RSI over the last 1000 bars, constrained between 60-80. Buy signals use the 10th percentile, constrained between 20-40. These thresholds recalculate on each bar based on recent data.
Ladder Box System
RSI movements are tracked in 2-point boxes. The indicator requires a 2-box reversal followed by 3 consecutive bars maintaining that reversal before generating a signal.
Dual Signal Output
Red down-triangles plot above price when the sell signal conditions are met. Green up-triangles plot below the price when buy signal conditions are met.
-------------------------------------------------------
REPAINTING
This indicator does not repaint. All calculations use "barstate.isconfirmed" to ensure signals appear only on closed bars. The request.security() call uses lookahead=barmerge.lookahead_off to prevent forward-looking bias.
-------------------------------------------------------
INTENDED CHART TIMEFRAME
This indicator is designed for use on 15-minute charts. The visual reminder table at the top of the chart indicates this requirement.
On a 15-minute chart:
RSI data comes from the 1-hour timeframe
Signals reflect 1-hour momentum shifts
3-bar confirmation equals 45 minutes of price action
Using it on other timeframes will change the higher timeframe RSI source and may produce different behavior.
-------------------------------------------------------
WHAT THIS INDICATOR DOES NOT DO
Does not predict future price movements
Does not provide entry or exit advice
Does not guarantee profitable trades
Does not replace comprehensive technical analysis
Does not account for fundamental factors, news events, or market structure
Does not adapt to all market conditions equally
-------------------------------------------------------
EDUCATIONAL USE
This indicator demonstrates one approach to momentum reversal detection using:
Multi-timeframe analysis
Adaptive thresholds via percentile calculation
Step-wise momentum tracking
Multi-bar confirmation logic
It is designed as a technical study, not a trading system. Signals represent calculated conditions based on RSI behavior, not trade recommendations. Always do your own analysis before taking market positions.
-------------------------------------------------------
RISK DISCLOSURE
Trading involves substantial risk of loss. This indicator:
Is for educational and informational purposes only
Does not constitute financial, investment, or trading advice
Should not be used as the sole basis for trading decisions
Has not been tested across all market conditions
May produce false signals, late signals, or no signals in certain conditions
Past performance of any indicator does not predict future results. Users must conduct their own analysis and risk assessment before making trading decisions. Always use proper risk management, including stop losses and position sizing appropriate to your account and risk tolerance.
MIT LICENSE
This code is open source and provided as-is without warranties of any kind. You may use, modify, and distribute it freely under the MIT License.
BTC Momentum Strategy Ver2.0 by @AshokTrendThe BTC Momentum Strategy with LazyBear SQZMOM & Custom SL + Angle Filter is a technical trading strategy that blends multiple proven concepts to capture favorable momentum trades in Bitcoin or other assets.
### Core Components
- **LazyBear Squeeze Momentum Indicator (SQZMOM):** This indicator identifies low volatility "squeeze" periods when Bollinger Bands contract inside Keltner Channels, signaling potential explosive moves once the squeeze releases. The strategy uses momentum derived from linear regression on price to judge trade direction—positive momentum favors longs, negative momentum favors shorts.
- **EMA 200 Trend Filter:** The 200-period Exponential Moving Average defines the prevailing trend. Trades are taken long only if price is above the EMA and short if below, reducing risk of countertrend entries.
- **Price Movement Angle Filter:** The strategy calculates the angle of recent price movement over a lookback period. Entries require a price angle greater than 27 degrees for longs and less than -27 degrees for shorts, confirming strong directional momentum and filtering out weak moves.
- **Stop Loss Management:** A custom stop loss in fixed points distance from the entry price manages risk, protecting capital if the market moves against the trade.
- **Trading Time Window:** The strategy trades only during Indian market hours (4:00 AM to 11:00 PM IST), filtering trades to relevant active market sessions.
- **Swing Levels:** Recent swing highs and lows are used as additional confirmation levels for entries and exits, helping to time trade triggers more precisely.
### How Trades Are Executed
- **Long Entry:** When trading hours are active, SQZMOM indicates bullish momentum (momentum histogram positive and squeeze released), price is in an uptrend (above EMA 200), the current close is above recent swing highs, and the price movement angle exceeds 27 degrees, the strategy enters a long position.
- **Short Entry:** When trading hours are active, SQZMOM shows bearish momentum (momentum histogram negative and squeeze released), price is in a downtrend (below EMA 200), the current close is below recent swing lows, and the price movement angle is less than -27 degrees, the strategy enters a short position.
- **Exits:** Positions are closed either when price breaches opposite swing levels, momentum conditions reverse, or trading hours end. Stop losses are also triggered if price moves unfavorably by the defined points.
### Strategy Benefits
- Detects volatility contractions and momentum expansions for potentially strong directional moves.
- Reduces false entries with the EMA trend and angle momentum filters.
- Manages risk actively with stop losses and time-based filters.
- Combines multiple technical tools — momentum, trend, volatility, price structure — for a holistic approach.
This strategy tends to work best on active higher timeframes where trends and momentum have clarity and is designed for disciplined, momentum-focused trading with robust trade management.
Concepts used-
SMC
TRednline Breaout,
Timefram-15M or Higher For better Result.
Note-We are not SEBI-Registered, Graphs, charts, and tables are provided for illustrative purposes only. Investing is subject to market risks. Investors acknowledge and accept the potential loss of some or all of an investment's value.Please consult your financial advisor before taking any decision.
Please whatsapp only=7835983697.
TRP Stop-Loss_Trailing SL# TRP Stop-Loss Indicator
## Overview
The TRP (True Range Percentage) Stop-Loss indicator is an advanced volatility-based stop-loss tool that provides dynamic position protection based on market volatility. Unlike traditional ATR-based indicators, TRP calculates volatility as a percentage of price, offering superior adaptability across different price ranges and market conditions.
## What is TRP and Why It's Superior to ATR
### TRP (True Range Percentage)
TRP calculates the true range as a percentage of the closing price, providing a **normalized volatility measure**. The formula is:
```
TRP = (True Range / Close) × 100
```
### Key Advantages of TRP over ATR:
1. **Price-Normalized Volatility**: TRP automatically adjusts for different price levels, making it equally effective whether you're trading a $10 stock or a $1000 stock.
2. **Percentage-Based Risk**: TRP gives you direct percentage risk values, making position sizing and risk management more intuitive.
3. **Better Cross-Market Comparison**: Unlike ATR, TRP allows you to compare volatility across different instruments on an equal basis.
4. **Adaptive to Market Conditions**: TRP naturally scales with price movements, providing more relevant stop-loss levels during trending markets.
5. **Consistent Risk Exposure**: Maintains consistent percentage risk regardless of the underlying asset's price level.
## Indicator Features
### 🎯 **Dual Stop-Loss System**
- **Long SL**: Red line below price for long positions
- **Short SL**: Blue line above price for short positions
- Independent control for each direction
### ⚙️ **Advanced Calculation Options**
#### **Multiple TRP Calculation Sources:**
- **Current Candle**: Uses real-time running candle data
- **Previous Close**: Uses completed candle data (default)
- **Last Green Candle**: For longs - uses TRP from the most recent bullish candle
- **Last Red Candle**: For shorts - uses TRP from the most recent bearish candle
#### **Independent Multipliers:**
- Separate multiplier controls for long and short stop-losses
- Adjust risk levels independently (0.1x to 10x+ range)
- Fine-tune stop-loss distance based on your risk tolerance
### 📊 **Visual Customization**
- **Line Styles**: Solid, dashed, or dotted lines
- **Custom Colors**: Separate color controls for long/short SL
- **Line Width**: Adjustable thickness (1-10)
- **Extension**: Customizable projection bars to the right
### 🏷️ **Smart Labeling System**
- **Value Display**: Shows exact SL price on the right side of lines
- **Toggle Control**: Enable/disable labels as needed
- **Size Options**: 5 different label sizes (tiny to huge)
- **Color Coordination**: Labels match their respective line colors
### ⏰ **Multi-Timeframe Support**
- Calculate TRP on any timeframe while viewing on another
- Default: Daily TRP calculation for intraday charts
- Maintains calculation integrity across timeframe switches
## How to Use
### Basic Setup:
1. Add the indicator to your chart
2. Select your preferred timeframe for TRP calculation
3. Choose calculation source for long and short positions
4. Adjust multipliers based on your risk tolerance
### Risk Management Applications:
- **Conservative**: Use 0.5-0.8 multipliers for tighter stops
- **Standard**: Use 1.0 multiplier for normal volatility-based stops
- **Aggressive**: Use 1.2-2.0 multipliers for wider stops in volatile markets
### Advanced Strategies:
- **Trend Following**: Use "Last Green/Red Candle" sources to adapt to momentum changes
- **Breakout Trading**: Use "Current Candle" for real-time stop adjustments
- **Swing Trading**: Use "Previous Close" for stable, confirmed levels
## Key Benefits
✅ **Dynamic Adaptation**: Automatically adjusts to changing market volatility
✅ **Percentage Risk Control**: Direct percentage-based risk management
✅ **Multi-Strategy Compatible**: Works with scalping, day trading, and swing trading
✅ **Visual Clarity**: Clean, professional chart display with customizable appearance
✅ **Real-Time Updates**: Instant recalculation when settings change
✅ **No Overlapping Lines**: Smart line management prevents chart clutter
## Best Practices
1. **Backtest First**: Test different multiplier settings on historical data
2. **Market Adaptation**: Adjust multipliers based on current market volatility regime
3. **Combine with Other Signals**: Use TRP stops with your existing entry signals
4. **Position Sizing**: Use TRP percentage values for consistent position sizing
5. **Regular Review**: Periodically review and adjust settings based on performance
## Technical Specifications
- **Pine Script Version**: v6
- **Overlay**: Yes (draws directly on price chart)
- **Calculations**: Based on 50-period EMA of TRP values
- **Updates**: Real-time with automatic line management
- **Performance**: Optimized for fast execution and minimal lag
This indicator is ideal for traders who want professional-grade, volatility-adaptive stop-loss management with the flexibility to fine-tune risk parameters across different market conditions and trading styles.
QZ Trend (Crypto Edition) v1.1a: Donchian, EMA, ATR, Liquidity/FThe "QZ Trend (Crypto Edition)" is a rules-based trend-following breakout strategy for crypto spot or perpetual contracts, focusing on following trends, prioritizing risk control, seeking small losses and big wins, and trading only when advantageous.
Key mechanisms include:
- Market filters: Screen favorable conditions via ADX (trend strength), dollar volume (liquidity), funding fee windows, session/weekend restrictions, and spot-long-only settings.
- Signals & entries: Based on price position relative to EMA and EMA trends, combined with breaking Donchian channel extremes (with ATR ratio confirmation), plus single-position rules and post-exit cooldowns.
- Position sizing: Calculate positions by fixed risk percentage; initial stop-loss is ATR-based, complying with exchange min/max lot requirements.
- Exits & risk management: Include initial stop-loss, trailing stop (tightens only), break-even rule (stop moves to entry when target floating profit is hit), time-based exit, and post-exit cooldowns.
- Pyramiding: Add positions only when profitable with favorable momentum, requiring ATR-based spacing; add size is a fraction of the base position, with layers sharing stop logic but having unique order IDs.
Charts display EMA, Donchian channels, current stop lines, and highlight low ADX, avoidable funding windows, and low-liquidity periods.
Recommend starting with 4H or 1D timeframes, with typical parameters varying by cycle. Liquidity settings differ by token; perpetuals should enable funding window filters, while spot requires "long-only" and matching fees. The strategy performs well in trends with quick stop-losses but faces whipsaws in ranges (filters mitigate but don’t eliminate noise). Share your symbol and timeframe for tailored parameters.
Margin Cost Calculator Screener - Taylor V1.2# Leverage Position Cost Calculator & Stop Lose Cost Screener #
Designed to provide traders with crucial insights into their leveraged positions directly on the TradingView chart.
Key Features:
> Dynamic Display: Choose to view only the estimated entry cost, or a comprehensive overview including potential losses at specific stop-loss levels, and a custom remark.
> Contract Size Input: Easily specify the contract size for your trades.
> Leverage Level Input: Set your desired leverage level, with helpful tooltips explaining the margin requirements for various leverage ratios (e.g., 25x, 10x, 5x) and an included fee estimate.
> Cost Calculation: Accurately calculates the estimated entry cost for your position based on the current market price, contract size, and leverage.
> Stop-Loss Projections: It projects potential losses for stop-loss orders set at 3% and 5% below the entry price, helping you manage risk effectively.
> Clear Table Visualization: All calculated data is presented in a clean, organized table anchored to the bottom-left of your chart, making it easy to reference at a glance.
> Symbol Identification: Automatically displays the short ticker symbol for the asset you are analyzing.
This tool is invaluable for traders who utilize leverage and need a quick, visual way to understand their financial exposure and potential outcomes before entering or managing a trade.
Sniper Swing — Short TF (Clean Signals) [v6]📘 How to Use the Sniper Swing Indicator
1. What It Does
It looks for short-term swing breaks in price.
It uses an oscillator (RSI/Stoch) and swing pivots to confirm moves.
It gives you 3 clear signals only:
BUY → Enter long (expecting price to go up).
Gay bear → Enter short (expecting price to go down).
EXIT → Close your trade (long or short).
Candles also change color:
Green = in a BUY trade.
Red = in a Gay bear trade.
Neutral (gray/none) = no trade.
2. When to Use
Works best on short timeframes (1m–5m) for scalping/intraday.
Use on liquid markets (MES/ES, NQ, SPY, BTC, ETH).
Avoid dead hours with no volume (like overnight futures lull or midday chop).
3. How to Trade With It
A. BUY trade
Wait for a BUY triangle below the candle.
Confirm:
Candle turned green.
Price broke a recent swing high.
Oscillator shows strength (indicator does this for you).
Enter long at the close of that candle.
Place your stop-loss:
At the yellow stop line (auto trailing stop), or
Just below the last swing low.
Stay in while candles are green.
Exit when:
An orange X appears, or
Price hits your stop.
B. Gay bear (short) trade
Wait for a Gay bear triangle above the candle.
Confirm:
Candle turned red.
Price broke a recent swing low.
Oscillator shows weakness.
Enter short at the close of that candle.
Place stop-loss:
At the yellow stop line, or
Just above the last swing high.
Stay in while candles are red.
Exit on an orange X or stop hit.
4. Pro Tips for New Traders
Only take one signal at a time → don’t double dip.
Quality > Quantity: ignore weak, sideways markets. Best signals happen during trends.
Start small: trade micros (MES) or small position sizes.
Use alerts: set TradingView alerts for BUY/Gay bear/EXIT so you don’t miss setups.
Think of the indicator like a navigator: it tells you the likely path, but you’re the driver → always manage risk.
5. Quick Mental Checklist
Signal? (BUY or Gay bear triangle)
Confirmed? (candle color + swing break)
Enter? (on close)
Stop? (yellow line or swing)
Exit? (orange X or stop)
2ATR / Close %Certainly. Here is the English version of the indicator description you requested.
---
### **2ATR Stop-Loss Ratio**
This indicator provides a straightforward calculation of **what percentage a 2ATR (Average True Range) move represents relative to the current price**. It's a specialized tool designed to help traders set dynamic, volatility-based stop-loss levels.
---
### **Purpose of the Indicator**
Many traders use a **2ATR** as their standard for setting a stop-loss, believing it's a good measure of a stock's typical movement. However, it can be difficult to quickly determine the exact percentage a 2ATR drop represents from the current price. This indicator solves that problem by giving you a clear, single number that shows the **anticipated percentage loss before you even enter a position**.
---
### **How It Works**
The indicator is calculated using a simple formula:
**(2 * ATR(20) / Current Price) * 100**
* `ATR(20)`: The Average True Range over the last 20 periods. This period can be customized in the indicator's settings.
* `Current Price`: The closing price at the time of calculation.
---
### **How to Use It**
* **Assess Risk**: A higher number on the indicator means greater volatility, indicating a wider stop-loss range.
* **Set a Stop-Loss**: If the indicator shows **3%**, it means a 2ATR move is roughly a 3% change from the current price. This gives you a clear understanding of the potential loss.
* **Adjust Position Size**: If the potential percentage loss is larger than you're comfortable with, you can use this information to reduce your position size, effectively managing your risk.
This tool is especially useful for trading highly volatile stocks, as it helps you establish a clear and effective risk management strategy.
Position Size CalculatorPosition Size Calculator
This open-source Pine Script® indicator helps traders manage risk by calculating position size, margin, and risk/reward based on account size, leverage, entry, stop-loss, and take-profit. It features a customizable table and optional chart lines/labels for clear trade planning across stocks, forex, crypto, and futures.
What It Does
- Position Size: Computes units to trade based on risk percentage and stop-loss distance, capped by leverage.
- Margin: Calculates initial margin in base currency and USD, with account size percentage.
- Risk/Reward: Shows risk-reward ratio, percentage price movements, and USD gains/losses.
- Visualization: Displays results in a table and optional chart lines/labels with customizable styles.
How It Works
- Precision: Adjusts price formatting using syminfo.mintick for accuracy across assets.
- Calculations: Position size = accountSize * (riskPercent / 100) / |entry - stoploss|, capped by accountSize * leverage / entry. Margin = positionSize / leverage. Risk-reward = |takeprofit - entry| / |stoploss - entry|.
- Display: Table shows metrics; optional lines/labels plot entry, stop-loss, and take-profit with percentage and USD details.
How to Use
- Set Inputs:
1- Account Size (USD): Your capital (e.g., 1000).
2- % Risk per Trade: Risk tolerance (e.g., 1%).
3- Leverage: Broker leverage (e.g., 1x, 10x).
4- Entry, Stop Loss, Take Profit: Trade prices.
5- Show Lines and Labels: Enable chart overlays.
- Customize: Adjust table position, colors, and line styles (Solid, Dashed, Dotted).
- View Results: Table shows position size, margin, and risk/reward. Chart lines/labels (if enabled) display prices, percentages, and USD outcomes.
- Apply: Use metrics for trade execution; modify code for custom features.
Notes
- Ensure valid inputs (entry ≠ stop-loss, both positive) to avoid “N/A”.
- Open-source: Inspect or extend the code for your needs.
- Contact the author via TradingView for feedback.
ATR SL/TPStop Loss Finder ATR
A Stop Loss Finder ATR indicator is a dynamic risk management tool leveraging the Average True Range (ATR) to identify and track optimal stop-loss levels based on current market volatility.
A stop hunt indicator is a technical tool designed to identify potential instances where large market participants, often referred to as "smart money," deliberately move the price to trigger a large number of stop-loss orders, creating a temporary price distortion before reversing the trend. These indicators aim to help traders detect these events to either avoid being stopped out or to enter trades in the direction of the anticipated reversal.
For example, a long wick below support with high volume may signal a bullish stop-hunt , indicating that the price has been driven down to trigger sell-stop orders before reversing upward. Conversely, a long wick above resistance with high volume may signal a bearish stop-hunt , suggesting the price was pushed up to trigger buy-stop orders before reversing downward. The presence of such wicks is often associated with candlestick patterns like hammers or shooting stars.
Unlike fixed stop-losses, this indicator adapts its distance from the current price using a customizable ATR multiplier, ensuring that stop-loss levels are neither too tight (prone to being triggered by normal market noise) nor too wide (exposing capital to excessive risk) . The core function calculates the true range—considering the current high-low range, gaps up, and gaps down—over a user-defined period (typically 14 bars), then applies a multiplier to generate a volatility-adjusted stop-loss distance . This approach allows the indicator to dynamically widen stops during high-volatility periods and tighten them during calm markets, providing a more responsive and context-aware exit strategy.
Imbalance RSI Divergence Strategy# Imbalance RSI Divergence Strategy - User Guide
## What is This Strategy?
This strategy identifies **imbalance** zones in the market and combines them with **RSI divergence** to generate trading signals. It aims to capitalize on price gaps left by institutional investors and large volume movements.
### Main Settings
- **RSI Period (14)**: Period used for RSI calculation. Lower values = more sensitive, higher values = more stable signals.
- **ATR Period (10)**: Period for volatility measurement using Average True Range.
- **ATR Stop Loss Multiplier (2.0)**: How many ATR units to use for stop loss calculation.
- **Risk:Reward Ratio (4.0)**: Risk-reward ratio. 2.0 = 2 units of reward for 1 unit of risk.
- **Use RSI Divergence Filter (true)**: Enables/disables the RSI divergence filter.
### Imbalance Filters
- **Minimum Imbalance Size (ATR) (0.3)**: Minimum imbalance size in ATR units to filter out small imbalances.
- **Enable Lookback Limit (false)**: Activates historical lookback limitations.
- **Maximum Lookback Bars (300)**: Maximum number of bars to look back.
### Visual Settings
- **Show Imbalance Size**: Displays imbalance size in ATR units.
- **Show RSI Divergence Lines**: Shows/hides divergence lines.
- **Divergence Line Colors**: Colors for bullish/bearish divergence lines.
### Volatility-Based Adjustments
- **Low volatility markets**:
- Minimum Imbalance Size: 0.2-0.4 ATR
- ATR Stop Loss Multiplier: 1.5-2.0
- **High volatility markets**:
- Minimum Imbalance Size: 0.5-1.0 ATR
- ATR Stop Loss Multiplier: 2.5-3.5
### Risk Tolerance
- **Conservative approach**:
- Risk:Reward Ratio: 2.0-3.0
- RSI Divergence Filter: Enabled
- Minimum Imbalance Size: Higher (0.5+ ATR)
- **Aggressive approach**:
- Risk:Reward Ratio: 4.0-6.0
- Minimum Imbalance Size: Lower (0.2-0.3 ATR)
###Market Conditions
- **Trending markets**: Higher RSI Period (21-28)
- **Sideways markets**: Lower RSI Period (10-14)
- **Volatile markets**: Higher ATR Multiplier
## Recommended Testing Procedure
1. **Start with default settings** and backtest on 3-6 months of historical data
2. **Adjust RSI Period** to see which value produces better results
3. **Optimize ATR Multiplier** for stop loss levels
4. **Test different Risk:Reward ratios** comparatively
5. **Fine-tune Minimum Imbalance Size** to improve signal quality
## Important Considerations
- **False positive signals**: Imbalances may be less reliable during low volatility periods
- **Market openings**: First hours often produce more imbalances but can be riskier
- **News events**: Consider disabling strategy during major news releases
- **Backtesting**: Test across different market conditions (trending, sideways, volatile)
## Recommended Settings for Beginners
**Safe settings for new users:**
- RSI Period: 14
- ATR Period: 14
- ATR Stop Loss Multiplier: 2.5
- Risk:Reward Ratio: 3.0
- Minimum Imbalance Size: 0.5 ATR
- RSI Divergence Filter: Enabled
## Advanced Tips
### Signal Quality Improvement
- **Combine with market structure**: Look for imbalances near key support/resistance levels
- **Volume confirmation**: Higher volume during imbalance formation increases reliability
- **Multiple timeframe analysis**: Confirm signals on higher timeframes
### Risk Management
- **Position sizing**: Never risk more than 1-2% of account per trade
- **Maximum drawdown**: Set overall stop loss for the strategy
- **Market hours**: Consider avoiding low liquidity periods
### Performance Monitoring
- **Win rate**: Track percentage of profitable trades
- **Average R:R**: Monitor actual risk-reward achieved vs. target
- **Maximum consecutive losses**: Set alerts for strategy review
This strategy works best when combined with proper risk management and market analysis. Always backtest thoroughly before using real money and adjust parameters based on your specific market and trading style.
Mutanabby_AI | ATR+ | Trend-Following StrategyThis document presents the Mutanabby_AI | ATR+ Pine Script strategy, a systematic approach designed for trend identification and risk-managed position entry in financial markets. The strategy is engineered for long-only positions and integrates volatility-adjusted components to enhance signal robustness and trade management.
Strategic Design and Methodological Basis
The Mutanabby_AI | ATR+ strategy is constructed upon a foundation of established technical analysis principles, with a focus on objective signal generation and realistic trade execution.
Heikin Ashi for Trend Filtering: The core price data is processed via Heikin Ashi (HA) methodology to mitigate transient market noise and accentuate underlying trend direction. The script offers three distinct HA calculation modes, allowing for comparative analysis and validation:
Manual Calculation: Provides a transparent and deterministic computation of HA values.
ticker.heikinashi(): Utilizes TradingView's built-in function, employing confirmed historical bars to prevent repainting artifacts.
Regular Candles: Allows for direct comparison with standard OHLC price action.
This multi-methodological approach to trend smoothing is critical for robust signal generation.
Adaptive ATR Trailing Stop: A key component is the Average True Range (ATR)-based trailing stop. ATR serves as a dynamic measure of market volatility. The strategy incorporates user-defined parameters (
Key Value and ATR Period) to calibrate the sensitivity of this trailing stop, enabling adaptation to varying market volatility regimes. This mechanism is designed to provide a dynamic exit point, preserving capital and locking in gains as a trend progresses.
EMA Crossover for Signal Generation: Entry and exit signals are derived from the interaction between the Heikin Ashi derived price source and an Exponential Moving Average (EMA). A crossover event between these two components is utilized to objectively identify shifts in momentum, signaling potential long entry or exit points.
Rigorous Stop Loss Implementation: A critical feature for risk mitigation, the strategy includes an optional stop loss. This stop loss can be configured as a percentage or fixed point deviation from the entry price. Importantly, stop loss execution is based on real market prices, not the synthetic Heikin Ashi values. This design choice ensures that risk management is grounded in actual market liquidity and price levels, providing a more accurate representation of potential drawdowns during backtesting and live operation.
Backtesting Protocol: The strategy is configured for realistic backtesting, employing fill_orders_on_standard_ohlc=true to simulate order execution at standard OHLC prices. A configurable Date Filter is included to define specific historical periods for performance evaluation.
Data Visualization and Metrics: The script provides on-chart visual overlays for buy/sell signals, the ATR trailing stop, and the stop loss level. An integrated information table displays real-time strategy parameters, current position status, trend direction, and key price levels, facilitating immediate quantitative assessment.
Applicability
The Mutanabby_AI | ATR+ strategy is particularly suited for:
Cryptocurrency Markets: The inherent volatility of assets such as #Bitcoin and #Ethereum makes the ATR-based trailing stop a relevant tool for dynamic risk management.
Systematic Trend Following: Individuals employing systematic methodologies for trend capture will find the objective signal generation and rule-based execution aligned with their approach.
Pine Script Developers and Quants: The transparent code structure and emphasis on realistic backtesting provide a valuable framework for further analysis, modification, and integration into broader quantitative models.
Automated Trading Systems: The clear, deterministic entry and exit conditions facilitate integration into automated trading environments.
Implementation and Evaluation
To evaluate the Mutanabby_AI | ATR+ strategy, apply the script to your chosen chart on TradingView. Adjust the input parameters (Key Value, ATR Period, Heikin Ashi Method, Stop Loss Settings) to observe performance across various asset classes and timeframes. Comprehensive backtesting is recommended to assess the strategy's historical performance characteristics, including profitability, drawdown, and risk-adjusted returns.
I'd love to hear your thoughts, feedback, and any optimizations you discover! Drop a comment below, give it a like if you find it useful, and share your results.
Extended CANSLIM Indicator❖ Extended CANSLIM Indicator.
The Extended CANSLIM indicator is an indicator that concentrates all the tools usually used by CANSLIM traders.
It shows a table where all the stock fundamental information is shown at once first for the last quarter and then up to 5 years back.
The fundamental data is checked against well known CANSLIM validation criteria and is shown over 4 state levels.
1. Good = Value is CANSLIM Compliant.
2. Acceptable = Value is not CANSLIM compliant but still good. value is shown with a lighter background color.
3. Warning = Value deserves special attention. Value is shown over orange background color.
3. Stop = Value is non CANSLIM compliant or indicates a stop trading condition. Value is shown over red background color.
The indicator has also a set of technical tools calculated on price or index and shown directly on the chart.
❖ Fundamental data shown in the table.
The table is arranged in 4 sets of data:
1. Table Header, showing Indicator and Company data.
2. CANSLIM.
3. 3Rs: RS Rating, Revenue and ROE.
4. Extra Data: Piotroski score, ATR, Trend Days, D to E, Avg Vol and Vol today.
Sets 3 and 4 can be hidden from the table.
❖ Indicator and Compay Data.
The table header shows, Indicator name and version.
It then displays Company Name, sector and industry, human size and its capitalization.
❖ CANSLIM Data.
Displays either genuine CANSLIM data from TradinView or custom data as best effort when that data cannot be obtained in TV.
C = EPS diluted growth, Quarterly YoY.
>= 25% = Good, >= 0% = Acceptable, < 0% = Stop
A = EPS diluted growth, Annual YoY.
>= 25% = Good, >= 0% = Acceptable, < 0% = Stop
N = New High as best effort (Cust).
Always Good
S = Float shares as best effort.
Always Good
L = One year performance relative to S&P 500 (Cust),
Positive : 0% .. 50% = Neutral, 50%+ = Leader, 80%+ = Leader+, 100%+ = Leader++
Negative : 0% .. -10% = Laggard, -10% .. -30% = Laggard+, -30%+ = Laggard++
>= 50% = Good, >= 0% = Acceptable, >= -10% Warning, < -10% = Stop
I = Accumulation/Distribution days over last 25 days as a clue for institutional support (Cust).
A delta is calculated by subtracting Distribution to Accumulation days.
> 0 = Good, = 0 = Acceptable, < 0 = Warning, < -5 = Stop
M = Market direction and exposure measured on S&500 closing between averages (Cust).
Varies from 0% Full Bear to 100% Full Bull
>= 80% = Good, >= 60% = Acceptable, >= 40% = Warning, < 40% = Stop
❖ Extra non CANSLIM Data.
RS = RS Rating.
>= 90 = Good, >= 80 = Accept, >= 50 = Warning, < 50 = Stop
Rev. = Revenue Growth Quarterly YoY.
>= 0% = Good, <0% = Stop
ROE = Return on Equity, Quarterly YoY.
>= 17% = Good, >= 0% = Acceptable, < 0% = Stop
Piotr. = Piotroski Score, www.investopedia.com (TV)
>= 7 = Good, >= 4 = Acceptable, < 4 = Stop
ATR = Average True Range over the last 20 days (Cust).
0% - 2% = Acceptable, 2% - 4% = Ideal, 4% - 6% = Warning, 5%+ = Stop.
Trend Days = Days since EMA150 is over EMA200 (Cust).
Always Good
D. to E. = Days left before Earnings. Maybe not a good idea buying just before earnings (Cust).
>= 28 = Good, >= 21 = Acceptable, >= 14 = Warning, < 14 = Stop
Avg Vol. = 50d Average Volume (Cust).
>= 100K = Good, < 100K = Acceptable
Vol. Today = Today's percentage volume compared to 50d average (Cust).
Always Good.
❖ Historical Data.
Optionally selectable historical data can be displayed for C, A, Revenue and ROE up to 20 quarters if available.
Quarterly numbers can also be displayed for A, C and Revenue.
Information can be shown in Chronological or Reverse Chronological order (default).
Increasing growth quarters are shown in white, while diminuing ones are shown in Yellow.
Transition from Losing to Profitable quarters are shown with an exclamation mark ‘!’
Finally, losing quarters are shown between parenthesis.
❖ MAs on chart.
Displays 200, 100, 50 and 20 days MAs on chart.
The MAs are also automatically scaled in the 1W time frame.
❖ New 52 Week High on chart.
A sun is shown on the chart the first time that a new 52 week high is reached.
The N cell shows a filled sun when a 52 week high is no older than a month, an lighter sun when it’s no older than a quarter or a moon otherwise.
❖ Pocket Pivots on chart.
Small triangles below the price are signaling pocket pivots.
❖ Bases on chart, formerly Darvas Boxes.
Draw bases as defined by Darvas boxes, both top or bottom of bases can be selected to be shown in order to only show resistance or support.
❖ Market exposure/direction indicator.
When charting S&P500 (SPX), Nasdaq 100 Index (NDX), Nasdaq composite (IXIC) or Dow Jownes Index (DJIA), the indicator switches to Market Exposure indicator, showing also Accumulation/Distribution days when volume information is available. This indication which varies from 0% to 100% is what is shown under the M letter in the CANSLIM table which is calculated on the S&P500.
❖ Follow Through Days indicator.
If you are an adept of the Low-cheat entry, then you will be highly interested by the Follow Through days indicator as measured in the S&P 500 and shown as diamonds on the chart.
The follow-through days are calculated on S&P500 but shown in current stock chart so you don’t need to chart the S&P 500 to know that a follow through day occurred.
Follow Through days show correctly on Daily time frame and most are also shown on the Weekly time frame as well.
They are also classified according to the market zone in which they occur:
0%-5% from peak = Pullback : FT day is not shown.
5%-10% from peak = Minor Correction : Minor FT days is shown.
10%-20% from peak = Correction : Intermediate FT days us shown
20+% from peak = Bear Market : Makor FT days is shown
❖ RS Line and Rating indicator.
A RS Line and Rating indicator can be added to the chart.
Relative Strength Rating Accuracy.
Please note that the RS Rating is not 100% accurate when compared to IBD values.
❖ Earning Line indicator.
An Earning Line indicator can be added to the chart.
❖ ATR Bands and ATR Trade calculator.
The motivation for this calculator came from my own need to enter trades on volatile stocks where the simple 7% Stop Loss rule doest not work.
It simply calculates the number of shares you can buy at any moment based on current stock price and using the lower ATR band as a stop loss.
A few words about the ATR Bands.
On this indicator the ATR bands are not drawn as a classical channel that follows the price.
The lower band is drawn as a support until it’s broken on a closing basis. It can’t be in a down trend.
The upper band is drawn as a resistance until it’s broken on a closing basis. It can’t be in an up trend.
The idea is that when price starts to fall down from a peak, it should not violate its lower band ATR and that means that we can use that level as a Stop Loss.
You must look back for the stock volatility and find out which ATR multiplier works well meaning that the ATR bands are not violated on normal pullbacks. By default, the indicator uses 5x multiplier.
❖ Extra things, visual features and default settings.
The first square cell of current quarter displays a check mark ‘V’ if the CANSLIM criteria is OK or acceptable or a cross ‘X’ otherwise.
The first square cell of historical C and Rev show respectively the count of last consecutive positive quarters.
There are different color themes from “Forest” to “Space” you can chose from to best fit your eyes.
You also have different table sizes going from “Micro” to “Huge” for better adjustment to the size of your display.
The default settings view show: Pocket Pivots, FT Days, MA50, RS Line and ATR Bands.
That's all, Enjoy!
Engulfing & Pin Bar Breakout StrategyOverview
This strategy automates a classic, powerful trading methodology based on identifying key candlestick reversal patterns and trading the subsequent price breakout. It is designed to be a complete, "set-and-go" system with built-in risk and position size management.
The core logic operates on the 1-Hour timeframe, scanning for four distinct high-probability reversal signals: two bullish and two bearish. An entry is only triggered when the market confirms the signal by breaking a key price level, aiming to capture momentum following a potential shift in market sentiment.
The Strategy Logic
The system is composed of two distinct modules: Bullish (Long) and Bearish (Short).
🐂 Bullish (Long) Setup
The script initiates a long trade based on the following strict criteria:
Signal: Identifies either a Hammer or a Bullish Engulfing pattern. These patterns often indicate that sellers are losing control and buyers are stepping in.
Confirmation: Waits for the very next candle after the signal.
Entry Trigger: A long position is automatically opened as soon as the price breaks above the high of the signal candle.
Stop Loss: Immediately set just below the low of the signal candle.
Take Profit: A fixed target is placed at a 1:5 Risk/Reward Ratio.
🐻 Bearish (Short) Setup
The script initiates a short trade based on the following strict criteria:
Signal: Identifies either a Shooting Star or a Bearish Engulfing pattern. These patterns suggest buying pressure is fading and sellers are taking over.
Confirmation: Waits for the very next candle after the signal.
Entry Trigger: A short position is automatically opened as soon as the price breaks below the low of the signal candle.
Stop Loss: Immediately set just above the high of the signal candle.
Take Profit: A fixed target is placed at a 1:4 Risk/Reward Ratio.
Key Feature: Automated Risk Management
This strategy is designed for disciplined trading. You do not need to calculate position sizes manually.
Fixed Risk: The script automatically calculates the correct position size to risk exactly 2% of your total account equity on every single trade.
Dynamic Sizing: The position size will adjust based on the distance between your entry price and your stop loss for each specific setup, ensuring a consistent risk profile.
How To Use
Apply the script to your chosen chart (e.g., BTC/USD).
Crucially, set your chart's timeframe to 1-Hour (H1). The strategy is specifically calibrated for this interval.
Navigate to the "Strategy Tester" tab below your chart to view backtest results, including net profit, win rate, and individual trades.
Disclaimer: This script is provided for educational and informational purposes only. It is not financial advice. All trading involves substantial risk, and past performance is not indicative of future results. Please use this tool responsibly and at your own risk.
Keltner Channel Based Grid Strategy # KC Grid Strategy - Keltner Channel Based Grid Trading System
## Strategy Overview
KC Grid Strategy is an innovative grid trading system that combines the power of Keltner Channels with dynamic position sizing to create a mean-reversion trading approach. This strategy automatically adjusts position sizes based on price deviation from the Keltner Channel center line, implementing a systematic grid-based approach that capitalizes on market volatility and price oscillations.
## Core Principles
### Keltner Channel Foundation
The strategy builds upon the Keltner Channel indicator, which consists of:
- **Center Line**: Moving average (EMA or SMA) of the price
- **Upper Band**: Center line + (ATR/TR/Range × Multiplier)
- **Lower Band**: Center line - (ATR/TR/Range × Multiplier)
### Grid Trading Logic
The strategy implements a sophisticated grid system where:
1. **Position Direction**: Inversely correlated to price position within the channel
- When price is above center line → Short positions
- When price is below center line → Long positions
2. **Position Size**: Proportional to distance from center line
- Greater deviation = Larger position size
3. **Grid Activation**: Positions are adjusted only when the difference exceeds a predefined grid threshold
### Mathematical Foundation
The core calculation uses the KC Rate formula:
```
kcRate = (close - ma) / bandWidth
targetPosition = kcRate × maxAmount × (-1)
```
This creates a mean-reversion system where positions increase as price moves further from the mean, expecting eventual return to equilibrium.
## Parameter Guide
### Time Range Settings
- **Start Date**: Beginning of strategy execution period
- **End Date**: End of strategy execution period
### Core Parameters
1. **Number of Grids (NumGrid)**: Default 12
- Controls grid sensitivity and position adjustment frequency
- Higher values = More frequent but smaller adjustments
- Lower values = Less frequent but larger adjustments
2. **Length**: Default 10
- Period for moving average and volatility calculations
- Shorter periods = More responsive to recent price action
- Longer periods = Smoother, less noisy signals
3. **Grid Coefficient (kcRateMult)**: Default 1.33
- Multiplier for channel width calculation
- Higher values = Wider channels, less frequent trades
- Lower values = Narrower channels, more frequent trades
4. **Source**: Default Close
- Price source for calculations (Close, Open, High, Low, etc.)
- Close price typically provides most reliable signals
5. **Use Exponential MA**: Default True
- True = Uses EMA (more responsive to recent prices)
- False = Uses SMA (equal weight to all periods)
6. **Bands Style**: Default "Average True Range"
- **Average True Range**: Smoothed volatility measure (recommended)
- **True Range**: Current bar's volatility only
- **Range**: Simple high-low difference
## How to Use
### Setup Instructions
1. **Apply to Chart**: Add the strategy to your desired timeframe and instrument
2. **Configure Parameters**: Adjust settings based on market characteristics:
- Volatile markets: Increase Grid Coefficient, reduce Number of Grids
- Stable markets: Decrease Grid Coefficient, increase Number of Grids
3. **Set Time Range**: Define your backtesting or live trading period
4. **Monitor Performance**: Watch strategy performance metrics and adjust as needed
### Optimal Market Conditions
- **Range-bound markets**: Strategy performs best in sideways trending markets
- **High volatility**: Benefits from frequent price oscillations around the mean
- **Liquid instruments**: Ensures efficient order execution and minimal slippage
### Position Management
The strategy automatically:
- Calculates optimal position sizes based on account equity
- Adjusts positions incrementally as price moves through grid levels
- Maintains risk control through maximum position limits
- Executes trades only during specified time periods
## Risk Warnings
### ⚠️ Important Risk Considerations
1. **Trending Market Risk**:
- Strategy may underperform or generate losses in strong trending markets
- Mean-reversion assumption may fail during sustained directional moves
- Consider market regime analysis before deployment
2. **Leverage and Position Size Risk**:
- Strategy uses pyramiding (up to 20 positions)
- Large positions may accumulate during extended moves
- Monitor account equity and margin requirements closely
3. **Volatility Risk**:
- Sudden volatility spikes may trigger multiple rapid position adjustments
- Consider volatility filters during high-impact news events
- Backtest across different volatility regimes
4. **Execution Risk**:
- Strategy calculates on every tick (calc_on_every_tick = true)
- May generate frequent orders in volatile conditions
- Ensure adequate execution infrastructure and consider transaction costs
5. **Parameter Sensitivity**:
- Performance highly dependent on parameter optimization
- Over-optimization may lead to curve-fitting
- Regular parameter review and adjustment may be necessary
## Suitable Scenarios
### Ideal Market Conditions
- **Sideways/Range-bound markets**: Primary use case
- **Mean-reverting instruments**: Forex pairs, some commodities
- **Stable volatility environments**: Consistent ATR patterns
- **Liquid markets**: Major currency pairs, popular stocks/indices
## Important Notes
### Strategy Limitations
1. **No Stop Loss**: Strategy relies on mean reversion without traditional stop losses
2. **Capital Requirements**: Requires sufficient capital for grid-based position sizing
3. **Market Regime Dependency**: Performance varies significantly across different market conditions
## Disclaimer
This strategy is provided for educational and research purposes only. Past performance does not guarantee future results. Trading involves substantial risk of loss and is not suitable for all investors. Users should thoroughly test the strategy and understand its mechanics before risking real capital. The author assumes no responsibility for trading losses incurred through the use of this strategy.
---
# KC网格策略 - 基于肯特纳通道的网格交易系统
## 策略概述
KC网格策略是一个创新的网格交易系统,它将肯特纳通道的力量与动态仓位调整相结合,创建了一个均值回归交易方法。该策略根据价格偏离肯特纳通道中心线的程度自动调整仓位大小,实施系统化的网格方法,利用市场波动和价格振荡获利。
## 核心原理
### 肯特纳通道基础
该策略建立在肯特纳通道指标之上,包含:
- **中心线**: 价格的移动平均线(EMA或SMA)
- **上轨**: 中心线 + (ATR/TR/Range × 乘数)
- **下轨**: 中心线 - (ATR/TR/Range × 乘数)
### 网格交易逻辑
该策略实施复杂的网格系统:
1. **仓位方向**: 与价格在通道中的位置呈反向关系
- 当价格高于中心线时 → 空头仓位
- 当价格低于中心线时 → 多头仓位
2. **仓位大小**: 与距离中心线的距离成正比
- 偏离越大 = 仓位越大
3. **网格激活**: 只有当差异超过预定义的网格阈值时才调整仓位
### 数学基础
核心计算使用KC比率公式:
```
kcRate = (close - ma) / bandWidth
targetPosition = kcRate × maxAmount × (-1)
```
这创建了一个均值回归系统,当价格偏离均值越远时仓位越大,期望最终回归均衡。
## 参数说明
### 时间范围设置
- **开始日期**: 策略执行期间的开始时间
- **结束日期**: 策略执行期间的结束时间
### 核心参数
1. **网格数量 (NumGrid)**: 默认12
- 控制网格敏感度和仓位调整频率
- 较高值 = 更频繁但较小的调整
- 较低值 = 较少频繁但较大的调整
2. **长度**: 默认10
- 移动平均线和波动率计算的周期
- 较短周期 = 对近期价格行为更敏感
- 较长周期 = 更平滑,噪音更少的信号
3. **网格系数 (kcRateMult)**: 默认1.33
- 通道宽度计算的乘数
- 较高值 = 更宽的通道,较少频繁的交易
- 较低值 = 更窄的通道,更频繁的交易
4. **数据源**: 默认收盘价
- 计算的价格来源(收盘价、开盘价、最高价、最低价等)
- 收盘价通常提供最可靠的信号
5. **使用指数移动平均**: 默认True
- True = 使用EMA(对近期价格更敏感)
- False = 使用SMA(对所有周期等权重)
6. **通道样式**: 默认"平均真实范围"
- **平均真实范围**: 平滑的波动率测量(推荐)
- **真实范围**: 仅当前K线的波动率
- **范围**: 简单的高低价差
## 使用方法
### 设置说明
1. **应用到图表**: 将策略添加到您所需的时间框架和交易品种
2. **配置参数**: 根据市场特征调整设置:
- 波动市场:增加网格系数,减少网格数量
- 稳定市场:减少网格系数,增加网格数量
3. **设置时间范围**: 定义您的回测或实盘交易期间
4. **监控表现**: 观察策略表现指标并根据需要调整
### 最佳市场条件
- **区间震荡市场**: 策略在横盘趋势市场中表现最佳
- **高波动性**: 受益于围绕均值的频繁价格振荡
- **流动性强的品种**: 确保高效的订单执行和最小滑点
### 仓位管理
策略自动:
- 根据账户权益计算最优仓位大小
- 随着价格在网格水平移动逐步调整仓位
- 通过最大仓位限制维持风险控制
- 仅在指定时间段内执行交易
## 风险警示
### ⚠️ 重要风险考虑
1. **趋势市场风险**:
- 策略在强趋势市场中可能表现不佳或产生损失
- 在持续方向性移动期间均值回归假设可能失效
- 部署前考虑市场制度分析
2. **杠杆和仓位大小风险**:
- 策略使用金字塔加仓(最多20个仓位)
- 在延长移动期间可能积累大仓位
- 密切监控账户权益和保证金要求
3. **波动性风险**:
- 突然的波动性激增可能触发多次快速仓位调整
- 在高影响新闻事件期间考虑波动性过滤器
- 在不同波动性制度下进行回测
4. **执行风险**:
- 策略在每个tick上计算(calc_on_every_tick = true)
- 在波动条件下可能产生频繁订单
- 确保充足的执行基础设施并考虑交易成本
5. **参数敏感性**:
- 表现高度依赖于参数优化
- 过度优化可能导致曲线拟合
- 可能需要定期参数审查和调整
## 适用场景
### 理想市场条件
- **横盘/区间震荡市场**: 主要用例
- **均值回归品种**: 外汇对,某些商品
- **稳定波动性环境**: 一致的ATR模式
- **流动性市场**: 主要货币对,热门股票/指数
## 注意事项
### 策略限制
1. **无止损**: 策略依赖均值回归而无传统止损
2. **资金要求**: 需要充足资金进行基于网格的仓位调整
3. **市场制度依赖性**: 在不同市场条件下表现差异显著
## 免责声明
该策略仅供教育和研究目的。过往表现不保证未来结果。交易涉及重大损失风险,并非适合所有投资者。用户应在投入真实资金前彻底测试策略并理解其机制。作者对使用此策略产生的交易损失不承担任何责任。
---
**Strategy Version**: Pine Script v6
**Author**: Signal2Trade
**Last Updated**: 2025-8-9
**License**: Open Source (Mozilla Public License 2.0)
Opening-Range BreakoutNote: Default trading date range looks mediocre. Set date range to "Entire History" to see full effect of the strategy. 50.91% profitable trades, 1.178 profit factor, steady profits and limited drawdown. Total P&L: $154,141.18, Max Drawdown: $18,624.36. High R^2
█ Overview
The Opening-Range Breakout strategy is a mechanical, session‑based day‑trading system designed to capture the initial burst of directional momentum immediately following the market open. It defines a user‑configurable “opening range” window, measures its high and low boundaries, then places breakout stop orders at those levels once the range closes. Built‑in filters on minimum range width, reward‑to‑risk ratios, and optional reversal logic help refine entries and manage risk dynamically.
█ How It Works
Opening‑Range Formation
Between 9:30–10:15 AM ET (configurable), the script tracks the highest high and lowest low to form the day’s opening range box.
On the first bar after the range window closes, the range high (OR_high) and low (OR_low) are “locked in.”
Range‑Width Filter
To avoid false breakouts in low‑volatility mornings, the range must be at least X% of the current price (default 0.35%).
If the measured opening-range width < minimum threshold, no orders are placed that day.
Entry & Order Placement
Long: a stop‑buy order at the opening‑range high.
Short: a stop‑sell order at the opening‑range low.
Only one side can trigger (or both if reverse logic is enabled after a losing trade).
Risk Management
Once triggered, each trade uses an ATR‑style stop-loss defined as a percentage retracement of the range (default 50% of range width).
Profit target is set at a configurable Reward/Risk Ratio (default 1.1×).
Optional: Reverse on Stop‑Loss – if the initial breakout loses, immediately reverse into the opposite side on the same day.
Session Exit
Any open positions are closed at the end of the regular trading day (default 3:45 PM ET window end, with hard flat at session close).
Visual cues are provided via green (range high) and red (range low) step‑line plots directly on the chart, allowing you to see the range box and breakout triggers in real time.
█ Why It Works
Early Momentum Capture: The first 15 – 60 minutes of trading encapsulate overnight news digestion and institutional order flow, creating a well‑defined volatility “range.”
Mechanical Discipline: Clear, rule‑based entries and exits remove emotional guesswork, ensuring consistency.
Volatility Filtering: By requiring a minimum range width, the system avoids choppy, low‑range days where false breakouts are common.
Dynamic Sizing: Stops and targets scale with the opening range, adapting automatically to each day’s volatility environment.
█ How to Use
Set Your Instruments & Timeframe
-Apply to any futures contract on a 1‑ to 5‑minute chart.
-Ensure chart timezone is set to America/New_York.
Configure Inputs
-Opening‑Range Window: e.g. “0930-1015” for a 45‑minute range.
-Min. OR Width (%): e.g. 0.35 for 0.35% of current price.
-Reward/Risk Ratio: e.g. 1.1 for a modest profit target above your stop.
-Max OR Retracement %: e.g. 50 to set stop at 50% of range width.
-One Trade Per Day: toggle to limit to a single breakout.
-Reverse on Stop Loss: toggle to flip direction after a losing breakout.
Monitor the Chart
-Watch the green and red range boundaries form during the session open.
-Orders will automatically submit on the first bar after the range window closes, conditioned on your filters.
Review & Adjust
-Backtest across multiple months to validate performance on your preferred contract.
-Tweak range duration, minimum width, and R/R multiple to fit your risk tolerance and desired win‑rate vs. expectancy balance.
█ Settings Reference
Input Defaults
Opening‑Range Window - Time window to form OR (HHMM-HHMM) - 0930–1015
Regular Trading Day - Full session for EOD flat (HHMM-HHMM) - 0930–1545
Min. OR Width (%) - Minimum OR size as % of close to trigger orders - 0.35
Reward/Risk Ratio - Profit target multiple of stop‑loss distance - 1.1
Max OR Retracement (%) - % of OR width to use as stop‑loss distance - 50
One Trade Per Day - Limit to a single breakout order per day - false
Reverse on Stop Loss - Reverse direction immediately after a losing trade - true
Disclaimer
This strategy description and any accompanying code are provided for educational purposes only and do not constitute financial advice or a solicitation to trade. Futures trading involves substantial risk, including possible loss of capital. Past performance is not indicative of future results. Traders should assess their own risk tolerance and conduct thorough backtesting and forward-testing before committing real capital.
Gann Single Square Swing Trading System with Gann AnglesGann Single Square Swing Trading System
This script automatically detects "squares" - geometric patterns where price movement equals time movement. When price moves the same distance as the number of bars (time), it creates powerful support/resistance levels based on Gann theory.
Key Visual Elements
• Box: The detected square pattern
• Dark Blue Line (50%): Most important trading level
• Green Lines: Profit target levels (125%, 150%)
• Red Lines: Stop loss levels (-25%, -50%)
• Colored Angle Lines: Gann angles for trend direction
• Quality Score: Blue label showing setup strength (aim for 70%+)
Simple Trading Rules
LONG Trades (Green 🟢 Square)
1. Entry: Buy when price touches the dark blue 50% line from above
2. Stop Loss: Place below the red -25% line
3. Take Profit: Exit at green 125% line (first target) or 150% line (second target)
SHORT Trades (Red 🔴 Square)
1. Entry: Sell when price touches the dark blue 50% line from below
2. Stop Loss: Place above the red -25% line
3. Take Profit: Exit at green 125% line (first target) or 150% line (second target)
Entry Checklist
✅ Square quality score > 70%
✅ Price touches 50% level (dark blue line)
✅ Volume above average (if volume filter enabled)
✅ Clear square formation visible
Alerts
The script generates automatic alerts when price reaches the 50% trading level. Enable alerts in TradingView to get notified of setups.
Bottom Line: Wait for the alert → Check quality score → Enter at 50% level → Set stop at red line → Take profit at green line.
Mickey's EMAMickey’s EMA is a lightweight, overlay indicator that combines two Exponential Moving Averages (EMAs) with automatic entry, stop-loss and target visual signals—plus dynamic JSON alerts for seamless webhook integration. It’s designed for both day-traders and swing-traders who want clear, on-chart cues and fully-customizable risk parameters.
🔍 Overview
Dual EMAs (fast & slow) to capture trend changes.
Automated “BUY” / “SELL” markers at every EMA crossover.
Customizable Stop-Loss % and Target % levels, plotted as ❌ and 🎯 bubbles.
“SL Hit (Custom)” if the opposite EMA crossover occurs before price touches your stop level.
JSON-formatted alerts containing ticker, instrument type, timeframe, trend (“CE” for bullish, “PE” for bearish), and price—ready for webhooks.
⚙️ Inputs
| Setting | Default | Description |
| ------------------------ | ------- | ----------------------------------------------- |
| **Fast EMA Length** | 20 | Period for the faster EMA. |
| **Slow EMA Length** | 200 | Period for the slower EMA. |
| **Price Source** | Close | Data series to calculate EMAs on. |
| **Custom Stop Loss %** | 0.1% | Stop-loss level as a percentage of entry price. |
| **Target %** | 0.5% | Profit-target level as a percentage of entry. |
| **Show Entry/SL/Target** | ON | Toggle all entry, SL and target visuals. |
📊 What It Plots
Fast EMA (blue) & Slow EMA (white) overlayed on price.
BUY 🟢 label below bar when Fast EMA crosses above Slow EMA.
SELL 🔴 label above bar when Fast EMA crosses below Slow EMA.
❌ (Custom) bubble at entry price if an opposite EMA crossover occurs before price hits your custom stop-loss.
❌ bubble at the stop-loss price when price actually breaches the stop level.
🎯 bubble at target price when price first reaches your profit-target level.
🔔 Alerts & Webhooks
On-screen alert conditions “Mickey’s EMA → BUY” and “Mickey’s EMA → SELL” appear in the Create-Alert dialog.
Dynamic JSON payload sent via alert() when a crossover fires, e.g.:
{
"script": "AAPL",
"scriptType": "equity",
"instrumentType": "NASDAQ",
"timeframe": "5",
"trend": "CE",
"price": 174.25
}
Use these alerts to integrate with bots, chat systems, manual, or any webhook-driven workflow.
🚀 Why Use Mickey’s EMA?
Clarity & Precision: All signals appear exactly at the EMA or price-level of interest.
Custom Risk Management: Define your own stop-loss and target percentages.
Seamless Automation: Dynamic JSON alerts mean zero manual setup for webhooks.
Versatile: Equally effective on intraday charts or daily/weekly timeframes.
Add Mickey’s EMA to your TradingView chart today and get instant, aesthetically-pleasing guidance on trend entries, risk exits, and profit targets—all in one elegant overlay.
Strategy Chameleon [theUltimator5]Have you ever looked at an indicator and wondered to yourself "Is this indicator actually profitable?" Well now you can test it out for yourself with the Strategy Chameleon!
Strategy Chameleon is a versatile, signal-agnostic trading strategy designed to adapt to any external indicator or trading system. Like a chameleon changes colors to match its environment, this strategy adapts to match any buy/sell signals you provide, making it the ultimate backtesting and automation tool for traders who want to test multiple strategies without rewriting code.
🎯 Key Features
1) Connects ANY external indicator's buy/sell signals
Works with RSI, MACD, moving averages, custom indicators, or any Pine Script output
Simply connect your indicator's signal output to the strategy inputs
2) Multiple Stop Loss Types:
Percentage-based stops
ATR (Average True Range) dynamic stops
Fixed point stops
3) Advanced Trailing Stop System:
Percentage trailing
ATR-based trailing
Fixed point trailing
4) Flexible Take Profit Options:
Risk:Reward ratio targeting
Percentage-based profits
ATR-based profits
Fixed point profits
5) Trading Direction Control
Long Only - Bull market strategies
Short Only - Bear market strategies
Both - Full market strategies
6) Time-Based Filtering
Optional trading session restrictions
Customize active trading hours
Perfect for day trading strategies
📈 How It Works
Signal Detection: The strategy monitors your connected buy/sell signals
Entry Logic: Executes trades when signals trigger during valid time periods
Risk Management: Automatically applies your chosen stop loss and take profit levels
Trailing System: Dynamically adjusts stops to lock in profits
Performance Tracking: Real-time statistics table showing win rate and performance
⚙️ Setup Instructions
0) Add indicator you want to test, then add the Strategy to your chart
Connect Your Signals:
imgur.com
Go to strategy settings → Signal Sources
1) Set "Buy Signal Source" to your indicator's buy output
2) Set "Sell Signal Source" to your indicator's sell output
3) Choose table position - This simply changes the table location on the screen
4) Set trading direction preference - Buy only? Sell only? Both directions?
imgur.com
5) Set your preferred stop loss type and level
You can set the stop loss to be either percentage based or ATR and fully configurable.
6) Enable trailing stops if desired
imgur.com
7) Configure take profit settings
8) Toggle time filter to only consider specific time windows or trading sessions.
🚀 Use Cases
Test various indicators to determine feasibility and/or profitability.
Compare different signal sources quickly
Validate trading ideas with consistent risk management
Portfolio Management
Apply uniform risk management across different strategies
Standardize stop loss and take profit rules
Monitor performance consistently
Automation Ready
Built-in alert conditions for automated trading
Compatible with trading bots and webhooks
Easy integration with external systems
⚠️ Important Notes
This strategy requires external signals to function
Default settings use 10% of equity per trade
Pyramiding is disabled (one position at a time)
Strategy calculates on bar close, not every tick
🔗 Integration Examples
Works perfectly with:
RSI strategies (connect RSI > 70 for sells, RSI < 30 for buys)
Moving average crossovers
MACD signal line crosses
Bollinger Band strategies
Custom oscillators and indicators
Multi-timeframe strategies
📋 Default Settings
Position Size: 10% of equity
Stop Loss: 2% percentage-based
Trailing Stop: 1.5% percentage-based (enabled)
Take Profit: Disabled (optional)
Trade Direction: Both long and short
Time Filter: Disabled
All SMAs Bullish/Bearish Screener (Enhanced)All SMAs Bullish/Bearish Screener Enhanced: Uncover High-Conviction Trend Alignments with Confidence
Description:
Are you ready to elevate your trading from mere guesswork to precise, data-driven decisions? The "All SMAs Bullish/Bearish Screener Enhanced" is not just another indicator; it's a sophisticated, yet user-friendly, trend-following powerhouse designed to cut through market noise and pinpoint high-probability trading opportunities. Built on the foundational strength of comprehensive Moving Average confluence and fortified with critical confirmation signals from Momentum, Volume, and Relative Strength, this script empowers you to identify truly robust trends and manage your trades with unparalleled clarity.
The Power of Multi-Factor Confluence: Beyond Simple Averages
In the unpredictable world of financial markets, true strength or weakness is rarely an isolated event. It's the harmonious alignment of multiple technical factors that signals a high-conviction move. While our original "All SMAs Bullish/Bearish Screener" intelligently identified stocks where price was consistently above or below a full spectrum of Simple Moving Averages (5, 10, 20, 50, 100, 200), this Enhanced version takes it a crucial step further.
We've integrated a powerful three-pronged confirmation system to filter out weaker signals and highlight only the most compelling setups:
Momentum (Rate of Change - ROC): A strong trend isn't just about price direction; it's about the speed and intensity of that movement. Positive momentum confirms that buyers are still aggressively pushing price higher (for bullish signals), while negative momentum validates selling pressure (for bearish signals).
Volume: No trend is truly trustworthy without the backing of smart money. Above-average volume accompanying an "All SMAs" alignment signifies strong institutional participation and conviction behind the move. It separates genuine trend starts from speculative whims.
Relative Strength Index (RSI): This versatile oscillator ensures the trend isn't just "there," but that it's developing healthily. We use RSI to confirm a bullish bias (above 50) or a bearish bias (below 50), adding another layer of confidence to the direction.
When the price aligns above ALL six critical SMAs, and is simultaneously confirmed by robust positive momentum, healthy volume, and a bullish RSI bias, you have an exceptionally strong "STRONGLY BULLISH" signal. This confluence often precedes sustained upward moves, signaling prime accumulation phases. Conversely, a "STRONGLY BEARISH" signal, where price is below ALL SMAs with negative momentum, confirming volume, and a bearish RSI bias, indicates powerful distribution and potential for significant downside.
How to Use This Enhanced Screener:
Add to Chart: Go to TradingView's Pine Editor, paste the script, and click "Add to Chart."
Customize Parameters: Fine-tune the lengths of your SMAs, RSI, Momentum, and Volume averages via the indicator's settings. Experiment to find what best suits your trading style and the assets you trade.
Choose Your Timeframe Wisely:
Daily (1D) and 4-Hour (240 min) are highly recommended. These timeframes cut through intraday noise and provide more reliable, actionable signals for swing and position trading.
Shorter timeframes (e.g., 15min, 60min) can be used by advanced day traders for very short-term entries, but be aware of increased volatility and noise.
Visual Confirmation:
Green/Red Triangles: Appear on your chart, indicating confirmed bullish or bearish signals.
Background Color: The chart background will subtly turn lime green for "STRONGLY BULLISH" and red for "STRONGLY BEARISH" conditions.
On-Chart Status Table: A clear table displays the current signal status ("STRONGLY BULLISH/BEARISH," or "SMAs Mixed") for immediate feedback.
Set Up Alerts (Your Primary Screener Tool): This is the game-changer! Create custom alerts on TradingView based on the "Confirmed Bullish Trade" and "Confirmed Bearish Trade" conditions. Receive instant notifications (email, pop-up, mobile) for any stock in your watchlist that meets these stringent criteria. This allows you to scan the entire market effortlessly and act decisively.
Strategic Stop-Loss Placement: The Trader's Lifeline
Even the most robust signals can fail. Protecting your capital is paramount. For this trend-following strategy, your stop-loss should be placed where the underlying trend structure is broken.
For a "STRONGLY BULLISH" Trade: Place your stop-loss just below the most recent significant swing low (higher low). This is the last point where buyers stepped in to support the price. If price breaks below this, your bullish thesis is invalidated.
For a "STRONGLY BEARISH" Trade: Place your stop-loss just above the most recent significant swing high (lower high). If price breaks above this, your bearish thesis is invalidated.
Alternatively, consider placing your stop-loss just below the 20-period SMA (for bullish trades) or above the 20-period SMA (for bearish trades). A significant close beyond this intermediate-term average often indicates a critical shift in momentum. Always ensure your chosen stop-loss adheres to your pre-defined risk per trade (e.g., 1-2% of capital).
Disciplined Profit Booking: Maximizing Gains
Just as important as knowing when you're wrong is knowing when to take profits.
Trailing Stop-Loss: As your trade moves into profit, trail your stop-loss upwards (for longs) or downwards (for shorts). You can trail it using:
Previous Swing Lows/Highs: Move your stop to just below each new higher low (for longs) or just above each new lower high (for shorts).
A Moving Average (e.g., 10-period or 20-period SMA): If price closes below your chosen trailing SMA, exit. This allows you to ride the trend while protecting accumulated profits.
Target Levels: Identify potential resistance levels (for longs) or support levels (for shorts) using pivot points, previous highs/lows, or Fibonacci extensions. Consider taking partial profits at these levels and letting the rest run with a trailing stop.
Loss of Confluence: If the "STRONGLY BULLISH/BEARISH" condition ceases to be met (e.g., RSI crosses below 50, or volume drops significantly), this can be a signal to reduce or exit your position, even if your stop-loss hasn't been hit.
The "All SMAs Bullish/Bearish Screener Enhanced" is your comprehensive partner in navigating the markets. By combining robust trend identification with critical confirmation signals and disciplined risk management, you're equipped to make smarter, more confident trading decisions. Add it to your favorites and unlock a new level of precision in your trading journey!
#PineScript #TradingView #SMA #MovingAverage #TrendFollowing #StockScreener #TechnicalAnalysis #Bullish #Bearish #QQQ #Momentum #Volume #RSI #SPY #TradingStrategy #Enhanced #Signals #Analysis #DayTrading #SwingTrading
BackTestLibLibrary "BackTestLib"
Allows backtesting indicator performance. Tracks typical metrics such as won/loss, profit factor, draw down, etc. Trading View strategy library provides similar (and more comprehensive)
functionality but only works with strategies. This libary was created to address performance tracking within indicators.
Two primary outputs are generated:
1. Summary Table: Displays overall performance metrics for the indicator over the chart's loaded timeframe and history
2. Details Table: Displays a table of individual trade entries and exits. This table can grow larger than the available chart space. It does have a max number of rows supported. I haven't
found a way to add scroll bars or scroll bar equivalents yet.
f_init(data, _defaultStopLoss, _defaultTakeProfit, _useTrailingStop, _useTraingStopToBreakEven, _trailingStopActivation, _trailingStopOffset)
f_init Initialize the backtest data type. Called prior to using the backtester functions
Parameters:
data (backtesterData) : backtesterData to initialize
_defaultStopLoss (float) : Default trade stop loss to apply
_defaultTakeProfit (float) : Default trade take profit to apply
_useTrailingStop (bool) : Trailing stop enabled
_useTraingStopToBreakEven (bool) : When trailing stop active, trailing stop will increase no further than the entry price
_trailingStopActivation (int) : When trailing stop active, trailing will begin once price exceeds base stop loss by this number of points
_trailingStopOffset (int) : When trailing stop active, it will trail the max price achieved by this number of points
Returns: Initialized data set
f_buildResultStr(_resultType, _price, _resultPoints, _numWins, _pointsWon, _numLoss, _pointsLost)
f_buildResultStr Helper function to construct a string of resutling data for exit tooltip labels
Parameters:
_resultType (string)
_price (float)
_resultPoints (float)
_numWins (int)
_pointsWon (float)
_numLoss (int)
_pointsLost (float)
f_buildResultLabel(data, labelVertical, labelOffset, long)
f_buildResultLabel Helper function to construct an Exit label for display on the chart
Parameters:
data (backtesterData)
labelVertical (bool)
labelOffset (int)
long (bool)
f_updateTrailingStop(_entryPrice, _curPrice, _sl, _tp, trailingStopActivationInput, trailingStopOffsetInput, useTrailingStopToBreakEven)
f_updateTrailingStop Helper function to advance the trailing stop as price action dictates
Parameters:
_entryPrice (float)
_curPrice (float)
_sl (float)
_tp (float)
trailingStopActivationInput (float)
trailingStopOffsetInput (float)
useTrailingStopToBreakEven (bool)
Returns: Updated stop loss for current price action
f_enterShort(data, entryPrice, fixedStopLoss)
f_enterShort Helper function to enter a short and collect data necessary for tracking the trade entry
Parameters:
data (backtesterData)
entryPrice (float)
fixedStopLoss (float)
Returns: Updated backtest data
f_enterLong(data, entryPrice, fixedStopLoss)
f_enterLong Helper function to enter a long and collect data necessary for tracking the trade entry
Parameters:
data (backtesterData)
entryPrice (float)
fixedStopLoss (float)
Returns: Updated backtest data
f_exitTrade(data)
f_enterLong Helper function to exit a trade and update/reset tracking data
Parameters:
data (backtesterData)
Returns: Updated backtest data
f_checkTradeConditionForExit(data, condition, curPrice, enableRealTime)
f_checkTradeConditionForExit Helper function to determine if provided condition indicates an exit
Parameters:
data (backtesterData)
condition (bool) : When true trade will exit
curPrice (float)
enableRealTime (bool) : When true trade will evaluate if barstate is relatime or barstate is confirmed; otherwise just checks on is confirmed
Returns: Updated backtest data
f_checkTrade(data, curPrice, curLow, curHigh, enableRealTime)
f_checkTrade Helper function to determine if current price action dictates stop loss or take profit exit
Parameters:
data (backtesterData)
curPrice (float)
curLow (float)
curHigh (float)
enableRealTime (bool) : When true trade will evaluate if barstate is relatime or barstate is confirmed; otherwise just checks on is confirmed
Returns: Updated backtest data
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor, _text_size)
f_fillCell Helper function to construct result table cells
Parameters:
_table (table)
_column (int)
_row (int)
_title (string)
_value (string)
_bgcolor (color)
_txtcolor (color)
_text_size (string)
Returns: Table cell
f_prepareStatsTable(data, drawTesterSummary, drawTesterDetails, summaryTableTextSize, detailsTableTextSize, displayRowZero, summaryTableLocation, detailsTableLocation)
f_fillCell Helper function to populate result table
Parameters:
data (backtesterData)
drawTesterSummary (bool)
drawTesterDetails (bool)
summaryTableTextSize (string)
detailsTableTextSize (string)
displayRowZero (bool)
summaryTableLocation (string)
detailsTableLocation (string)
Returns: Updated backtest data
backtesterData
backtesterData - container for backtest performance metrics
Fields:
tradesArray (array) : Array of strings with entries for each individual trade and its results
pointsBalance (series float) : Running sum of backtest points won/loss results
drawDown (series float) : Running sum of backtest total draw down points
maxDrawDown (series float) : Running sum of backtest total draw down points
maxRunup (series float) : Running sum of max points won over the backtest
numWins (series int) : Number of wins of current backtes set
numLoss (series int) : Number of losses of current backtes set
pointsWon (series float) : Running sum of points won to date
pointsLost (series float) : Running sum of points lost to date
entrySide (series string) : Current entry long/short
tradeActive (series bool) : Indicates if a trade is currently active
tradeComplete (series bool) : Indicates if a trade just exited (due to stop loss or take profit)
entryPrice (series float) : Current trade entry price
entryTime (series int) : Current trade entry time
sl (series float) : Current trade stop loss
tp (series float) : Current trade take profit
defaultStopLoss (series float) : Default trade stop loss to apply
defaultTakeProfit (series float) : Default trade take profit to apply
useTrailingStop (series bool) : Trailing stop enabled
useTrailingStopToBreakEven (series bool) : When trailing stop active, trailing stop will increase no further than the entry price
trailingStopActivation (series int) : When trailing stop active, trailing will begin once price exceeds base stop loss by this number of points
trailingStopOffset (series int) : When trailing stop active, it will trail the max price achieved by this number of points
resultType (series string) : Current trade won/lost
exitPrice (series float) : Current trade exit price
resultPoints (series float) : Current trade points won/lost
summaryTable (series table) : Table to deisplay summary info
tradesTable (series table) : Table to display per trade info